$(function () {
    /*** Grab global url params ***/
    //var filter = $(document).getUrlParam("filter");
    var curpage = $("body").attr("id").split("page_")[1];
	var cursubpage = $.trim($("body").attr("class").split("subpage_")[1]);
	var cursubpage = cursubpage.split(' ')[0];

    var iOS = false;
    if (navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
        iOS = true;
    }

	function loadSlideShow(slideshow, init)
	{
		var totalImages = $(slideshow + " img").length;
		var firstImage = $(slideshow + " img:first");
		var loadCount = 0;

		$(slideshow + " img").one('load', function(){
			
			$(this).addClass('loaded');
			
			loadCount++;
			
			if (totalImages === loadCount)
			{
				$(slideshow).siblings('.loader').hide('fade', 300, function(){
					$(slideshow).show();
					
					if (init !== undefined) {
						$(slideshow).slideShow(init);
					} else {
						$(slideshow).slideShow();
					}
				});
			}
		})
		.each(function(){
			if (this.complete)
			{
				$(this).trigger('load');
			}
		});
	}
	
	if (curpage === 'home') { loadSlideShow("#feature_slideshow", {'controls': false, 'nav': true }); }
	if (curpage === 'work') {
		if (cursubpage === 'photo_gallery') { loadSlideShow("#gallerySlides"); }
		if (cursubpage === 'video_gallery') { loadSlideShow("#gallerySlides"); }
		if (cursubpage === 'featured_work') { loadSlideShow("#gallerySlides"); }
		if (cursubpage === 'digital_gallery') { loadSlideShow("#gallerySlides"); }
	}
	
    $(".subnav li").hover(
        function () {
            if ($(this).hasClass("navon")) { $(this).attr("navon", "true"); } else { $(this).attr("navon", "false"); }
            $(this).addClass("navon");
        },
        function () {
            if ($(this).attr("navon") != "true") {
                $(this).removeClass("navon");
            }
        }
    );

    //feature_block animation
    if (!iOS) {
        $(".feature_block ul li").hover(
			function () {
			    $(this).find("a.overlay").stop(true, true).fadeTo(300, 0.6);
			},
			function () {
			    if (!$(this).hasClass('active')) {
			        $(this).find("a.overlay").fadeOut(300);
			    }
			}
		);
    }
	
	$('.iOSHover').bind('touchstart touchend', function(e) {
		e.preventDefault();
		$(this).toggleClass('ios_hover_effect');
	});
	
	$('.no-csstransforms3d .flipperWrapper').hover(
		function() {
			//var height = $(this).height();
			$(this).find('.flipper .back').stop(true, true).toggle('fade', 800);
			$(this).find('.flipper .front').stop(true, true).toggle('fade', 800);
			//$(this).find('.flipper .front').toggle('fade', 200);
			//$(this).find('.flipper .back').show();
			//$(this).find('.flipper').stop().animate({top: '-' + height + 'px'}, 200);
		},
		function() {
			//$(this).find('.flipper .front').toggle();
			$(this).find('.flipper .back').stop(true, true).toggle('fade', 800);
			$(this).find('.flipper .front').stop(true, true).toggle('fade', 800);
			//$(this).find('.flipper').stop().animate({top: '0'}, 250);
		}
	);
	
    /*** Contact Us ***/
    $("#firstname").blur(function () {
        if ($.trim($(this).val()) == "") { $(this).css("background-color", "Red"); } else { $(this).css("background-color", "White"); }
    });
    $("#lastname").blur(function () {
        if ($.trim($(this).val()) == "") { $(this).css("background-color", "Red"); } else { $(this).css("background-color", "White"); }
    });
    $("#email").blur(function () {
        if (($.trim($(this).val()) == "") || (mvalidate("email", ($.trim($(this).val()), true) == false))) { $(this).css("background-color", "Red"); } else { $(this).css("background-color", "White"); }
    });
    $("#phone").blur(function () {
        if (($.trim($(this).val()) != "") && (mvalidate("phone", ($.trim($(this).val()), true) == false))) { $(this).css("background-color", "Red"); } else { $(this).css("background-color", "White"); }
    });

    $("#btn_contactus").click(function () {
        $("#cu_loader").show();

        var firstname = $("#firstname").val();
        var lastname = $("#lastname").val();
        var title = $("#title").val();
        var company = $("#company").val();
        var email = $("#email").val();
        var phone = $("#phone").val();
        var reason = $("#reason").val();
        var message = $("#message").val();
        var howhear = $("#howhear").val();

        var haserror = false;
        var errormsg = "";

        if (($.trim(phone) != "") && (mvalidate("phone", ($.trim(phone), true) == false))) { $("#phone").css("border-color", "Red"); haserror = true; errormsg = "Please enter a valid phone number."; } else { $("#phone").css("border-color", "#666"); }
        if (($.trim(email) == "") || (mvalidate("email", ($.trim(email), true) == false))) { $("#email").css("border-color", "Red"); haserror = true; errormsg = "Please enter a valid email address."; } else { $("#email").css("border-color", "#666"); }
        if ($.trim(lastname) == "") { $("#lastname").css("border-color", "Red"); haserror = true; errormsg = "Please enter a valid last name."; } else { $("#lastname").css("border-color", "#666"); }
        if ($.trim(firstname) == "") { $("#firstname").css("border-color", "Red"); haserror = true; errormsg = "Please enter a valid first name."; } else { $("#firstname").css("border-color", "#666"); }

        var querystring = "firstname=" + firstname + "&lastname=" + lastname + "&title=" + title + "&company=" + company;
        querystring += "&email=" + email + "&phone=" + phone + "&reason=" + reason + "&message=" + encodeURIComponent(message);
        querystring += "&howhear=" + encodeURIComponent(howhear) + "&timestamp=" + new Date().getTime();

        if (!haserror) {
            $.ajax({
                type: "POST",
                url: "lib/contact.php",
                data: querystring,
                success: function (msg) {
                    if (msg == "Thank you for your interest.") {
                        $("#cu_errortext").hide()
                        //$("#contactusform").hide();
                        $("#contactusform").html('<div style="margin-top: 82px;">Thank you for your interest in <span class="bolded italic">iNDELIBLE</span>. A representative will<br/>contact you shortly.</div>');
                        window.scrollTo(0, 0);

                        if ($("#rightcol").height() < $("#leftcol").outerHeight()) {
                            $("#rightcol").height($("#leftcol").outerHeight());
                        } else {
                            $("#leftcol").height($("#rightcol").height() - 60);
                        }
                        $("#cu_loader").hide();
                    } else {
                        $("#cu_errortext").show().html(msg);
                        window.scrollTo(0, 0);
                        $("#cu_loader").hide();
                    }
                }
            });
        } else {
            $("#cu_errortext").show().html(errormsg);
            window.scrollTo(0, 0);
            $("#cu_loader").hide();
        }


    });

    /*** Clients ***/
    var img;
    //$("#clients_list li").hover(
    $("#clients_list li.cf_casestudy").hover(
        function () {
            img = $(this).find("img");
            img.attr("src", img.attr("src").replace("_bw", "_color"));
        },
        function () {
            img = $(this).find("img");
            img.attr("src", img.attr("src").replace("_color", "_bw"));
        }
    );

    if (curpage == "clients") { if (isdefined('filter')) filterClients(filter); }

    $("#client_viewall").click(function () { filterClients(); });
    $("#client_casestudy").click(function () { filterClients('casestudy'); });

    $("#subnav_clients li").click(function () {
        var myfilter = $(this).attr("id").split("subnav_")[1];
        filterClients(myfilter);
    });

    /*** Work ***/
    /*
    $("#work_list li").hover(
    function () {
    $(this).children(".work_overlay").stop().fadeTo(300, 1);
    },
    function () {
    $(this).children(".work_overlay").stop().fadeTo(300, 0);
    }
    );
    */

    if (curpage == "work") { if (isdefined('filter')) filterWork(filter); }

    $("#work_viewall").click(function () { filterWork(); });

    $("#subnav_work_services li").click(function () {
        var myfilter = $(this).attr("id").split("subnav_")[1];
        filterWork(myfilter);
    });

    $("#subnav_work_industry li").click(function () {
        var myfilter = $(this).attr("id").split("subnav_")[1];
        filterWork(myfilter);
    });

    /*** News ***/
    if ((curpage == "press") || (curpage == "news")) {
        if (isdefined('filter')) filterPress(filter);
        //what is this?
        // $("#page_news .g_gutter").height($("#g_shell").innerHeight());
    }

    $("#press_viewall").click(function () { filterPress(); });
    $("#subnav_press li").click(function () {
        var myfilter = $(this).attr("id").split("subnav_")[1];
        filterPress(myfilter);
    });
    $("#subnav_press_archive li").click(function () {
        var myfilter = $(this).attr("id").split("subnav_")[1];
        filterPress(myfilter);
    });

    $("#article_decks .article_deck").hover(
        function () {
            $(this).find(".deck_hasimage .deck_overlay").stop(true, true).fadeIn();
        },
        function () {
            $(this).find(".deck_hasimage .deck_overlay").fadeOut();
        }
    );

    /*** Careers ***/
    if (curpage == "careers") {
        if ($("#careerstext .jobdescr_block").length > 0) {
            $("#careerstext .jobdescr_block:first").show();
        }
        $("#jobs_nav li.hiring:first").css({ color: '#ff0c36' });
    }
    $("#jobs_nav .hiring").click(function () {
        $("#jobs_nav li.hiring").each(function () { $(this).css({ color: '#fff' }); });
        window.scrollTo(0, 0);
        var myid = $(this).attr("id").split("jobnav_")[1];
        var descrid = "jobdescr_" + myid;
        $(this).css({ color: '#ff0c36' });
        $("#careerstext .jobdescr_block").hide();
        $("#" + descrid).show();
    });

    $(window).konami(function () {
        randomFade();
    });
});

var randomFadeCalls = 0;
function randomFade() {
    if (randomFadeCalls < 10) {
        $("#innerwrapper li").each(function () {
            var secs = randomFromTo(200, 4000);
            $(this).fadeOut(secs);
            $(this).fadeIn(secs);
        });
        randomFade();
        randomFadeCalls++;
    }
}

function randomFromTo(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
}


function filterPress(infilter) {
    var presslist = $("#page_news .article_deck");
    if ((infilter == null) || (infilter == "")) {
        presslist.show();
        $("#page_news .g_gutter").height($("#g_shell").innerHeight());
        $(".subnav li").removeClass("navon").attr("navon", "false");
    }
    else {
        var filterclass = "af_" + infilter;
        presslist.hide();
        $("#page_news ." + filterclass).show();
        $(".subnav li").removeClass("navon").attr("navon", "false");
        $("#subnav_" + infilter).addClass("navon").attr("navon","true");
    }
}

function filterClients(infilter) {
    var clientlist = $("#clients_list li");
    if ((infilter == null) || (infilter == "")) {
        clientlist.show();
        $(".subnav li").removeClass("navon").attr("navon", "false");
    } else {
        var filterclass = "cf_" + infilter;
        clientlist.hide();
        $("#clients_list li." + filterclass).show();
        $(".subnav li").removeClass("navon").attr("navon", "false");
        $("#subnav_" + infilter).addClass("navon").attr("navon", "true");
    }
}

function filterWork(infilter) {
    var worklist = $("#featured_work_list li");
    if ((infilter == null) || (infilter == "")) {
        worklist.show();
        $(".subnav li").removeClass("navon").attr("navon", "false");
    } else {
        var filterclass = "wf_" + infilter;
        worklist.hide();
        $("#featured_work_list li." + filterclass).show();
        $(".subnav li").removeClass("navon").attr("navon", "false");
        $("#subnav_" + infilter).addClass("navon").attr("navon", "true");
    }
}

var geocoder;
var map;
function initializeMap() {
    var myLatlng = new google.maps.LatLng(40.753946, -73.992397);
    geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': '535 8th ave, New York, NY' }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            myLatlng = results[0].geometry.location;
        }
    });

    var myOptions = {
        zoom: 15,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        streetViewControl: true

    }
    var map = new google.maps.Map(document.getElementById("cu_googlemap"), myOptions);
    var beachMarker = new google.maps.Marker({
        position: myLatlng,
        map: map
    });

    var contentString = '<div style="overflow: hidden; width:180px; height: 49px; margin: 5px 0pt 0pt 14px;"><img src="../images/contactus/indelible_logo_googlemaps.png" alt="iNDELIBLE"/></div>';

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    infowindow.open(map, beachMarker);
    /*
    var panorama = map.getStreetView();
    panorama.setPosition(myLatlng);
    panorama.setPov({heading:300,pitch:0,zoom:1});
    panorama.setVisible(true);*/

}

function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initializeMap";
    document.body.appendChild(script);
}


function mvalidate(ftype, val, req) {
    if ((ftype == null) || (ftype == "")) { return false; }
    switch (ftype) {
        case "text":
            var re = /[^a-zA-Z\- ]/g;
            if ((req) && (val == "")) {
                return false;
            } else if (re.test(val)) {
                return false;
            } else {
                return true;
            }
            break;
        case "int":
            var re = /[\D]/g;
            if (re.test(val)) { return false; } else { return true; }
            break;
        case "email":
            var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
            return re.test(val);
            break;
        case "alpha":
            var re = /[^a-zA-Z]/g;
            if (re.test(val)) { return false; } else { return true; }
            break;
        case "phone":
            var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/;
            return re.test(val);
            break;
        case "date":
            var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/;
            if (!re.test(val)) return false;
            var result = val.match(re);
            var m = parseInt(result[1]);
            var d = parseInt(result[2]);
            var y = parseInt(result[3]);
            if (m < 1 || m > 12 || y < 1900 || y > 2100) return false;
            if (m == 2) {
                var days = ((y % 4) == 0) ? 29 : 28;
            } else if (m == 4 || m == 6 || m == 9 || m == 11) {
                var days = 30;
            } else {
                var days = 31;
            }
            return (d >= 1 && d <= days);
            break;
        case "pass":
            return true;
            break;
        default:
            return false;
    }
}

function isdefined(variable) {
    return (typeof (window[variable]) == "undefined") ? false : true;
}

