/*
// type3 digital scriptoids by
// ---------------------------
//      jared at type3digital.com
//      christopher at type3digital.com
//		alex at type3digital.com
*/

$(document).ready(function(){
   if (typeof kw_list != 'undefined') keywordSelect(kw_list);
   if ($('.get-involved').length) { setupNewsletterForm(); }
   if ($('.talk-to-us').length) { setupCallbackForm(); }
   if ($('.tweetform').length) { setupTweetForm(); }    
   if ($("#logo_flash").length) { embedFlash("logo", 650, 145, true, false); }
   if ($("#clients_flash").length) { embedFlash("clients", 240, 159, true, true); }
   if ($("#book_flash").length) { embedFlash("book", 1000, 1000, false, false); }   
    if ($(".highScoreStart").length) { setupHighScore();  }   
	if ($("#tab-bottom").length) { showTab(1);  } 

   applyEmails();   
   
   goBack();

	closeBanners();
	
	openBanner();
});

goBack = function(){
	$('#portfolio-back').click(function(event){
		event.preventDefault();
		window.history.back();
	});
}

setupHighScore = function() {

	$(".highScoreStart").click(function(){
   		embedHighScore("high-score-game", true, false);
		if(pageTracker._trackEvent){
			pageTracker._trackEvent("Talk to us", "Button Clicked");
		}
	});
	
};

closeBanners = function(){
	$('.close').click(function(){
		
		$(this).parent().parent().css("display","none");
		$('#gamethumb').css("display","block");
		
		
		return false;
		});
}

openBanner = function(){
	$('.open').click(function(){
		
		var filetoload = $(this).attr('name');
		
		$('.game').each(function(){
			if($(this).css({"display":"block"})){
				$(this).css({"display":"none"});
			}	
		});
		
		$('#' + filetoload).css("display","block");
		$('#gamethumb').css("display","none");
		
		return false;
	});
}

talkformSubmit = function(){
		if(pageTracker._trackEvent){
			pageTracker._trackEvent("Talk to us", "Form Submited");
		}
}

talkformFail = function(){
		if(pageTracker._trackEvent){
			pageTracker._trackEvent("Talk to us", "Form Failed");
		}
}

bookTracking = function(action){
	if(pageTracker._trackEvent){
		pageTracker._trackEvent("Journey of a Website", action);		
	}	
}

applyEmails = function() {
        
    buildEmail("sanfrancisco","emSanFran");
    buildEmail("london","emLondon");
	buildEmail("emma","emEmma");
	buildEmail("kimberly","emKim");
	buildEmail("jobs","emJobs");
}

buildEmail = function(input, span) {

    // common
    var em3 = "com";
    var em2 = "type3digital";
    var lnk1 = "<a href=";
    var lnk2 = "\"mailto:";
    var lnk3 = "\">";
    var lnk4 = "</a>";
    
    $('#' + span).html(lnk1 + lnk2 + input + "@" + em2
        + "." + em3 + lnk3 + input + "@" 
        + em2 + "." + em3 + lnk4);
}



showHide = function(show,hide,label) { 
    jQuery.each(show.split(','), function() {
        $('#' + this).css("display","block");
    });
    jQuery.each(hide.split(','), function() {
        $('#' + this).css("display","none");
    });
       
    // contact-us page only 
    if (typeof label != 'undefined' &&  typeof map != 'undefined' ) {
        showMap(label);
    }
}

keywordSelect = function(keywords) {
    $('#' + 'kw_ul').children('li').attr('class', '');


    $.each(keywords.split(','), function() {
        $('#' + this).attr('class', 'selected');
        //$("#kwDesc p").hide();
        if ($(".kwDesc").length) { $("#kwDesc_" + this).show(); }
    });
}

embedFlash = function(vUrl, vWidth, vHeight, vTransparent, vPreloader, vDiv) {
	
	var params     = {};
	var flashvars  = {};
	var attributes = {};

	params.menu                 = "false";
	params.quality              = "high";
	params.allowFullScreen      = "true";
	params.base				    = ".";
	params.salign	   		    = "tl";
	params.scale 			    = "default";
	
	if (vTransparent == true) {
		params.wmode = "transparent";
		attributes.wmode = "transparent";
	}
	
	if(typeof(vDiv) === 'undefined') {
		vDiv = vUrl + '_flash';	
	}
	
	attributes.allowFullScreen  = "true";
	attributes.id			    = vDiv;
	attributes.bgcolor 	  	    = "#000000";
	
	if (vPreloader == false) {
		swfobject.embedSWF("/swf/"+vUrl+".swf", vDiv, vWidth, vHeight, "8.0.0", "swf/expressinstall.swf", flashvars, params, attributes);
	} else {
		flashvars.vUrl = vUrl+".swf";
		swfobject.embedSWF("/swf/preloader.swf", vDiv, vWidth, vHeight, "8.0.0", "swf/expressinstall.swf", flashvars, params, attributes);
	}
	swfobject.createCSS("#"+attributes.id,"outline:none"); 
}


embedHighScore = function(vUrl, vTransparent, vPreloader) {
	
	var params     = {};
	var flashvars  = {};
	var attributes = {};
	
	var vWidth = $(window).width();
	var vHeight = $(window).height();
	var div = "overlay";

	params.menu                 = "false";
	params.quality              = "high";
	params.allowFullScreen      = "true";
	params.base				    = ".";
	params.salign	   		    = "tl";
	params.scale 			    = "default";
	params.wmode	   	        = "transparent";
	
	attributes.allowFullScreen  = "true";
	attributes.id			    = "overlay"
	attributes.bgcolor 	  	    = "#000000";
	attributes.wmode	   	    = "transparent";
	
	flashvars.vUrl = vUrl+".swf";	
	swfobject.embedSWF("/swf/"+vUrl+".swf", div, vWidth, vHeight, "9.0.0", "swf/expressinstall.swf", flashvars, params, attributes);
	swfobject.createCSS("#"+attributes.id,"outline:none"); 
	
	resizeOverlay();	
	
	setTimeout(function() {
		$('#overlay').focus();						
	}, 500);
	
	$(window).resize(function() {			
		resizeOverlay();	
	}).scroll(function() {		
		resizeOverlay();		
	});
}

removeOverlay = function() {

	$('#overlay').remove();
	$('body').prepend('<div id="overlay"></div>');	

}

resizeOverlay = function() {

	var vWidth = $(window).width();
	var vHeight = $(window).height();
	var vScrollPos = $(window).scrollTop();
	$('#overlay').attr("width",vWidth);
	$('#overlay').attr("height",vHeight);
	$('#overlay').css({ top:vScrollPos });
	$('#overlay').focus();

}	

embedVideo = function(vUrl, vWidth, vHeight, vName, vDisable) {
	var params     = {};
	var flashvars  = {};
	var attributes = {};
	
	params.menu                 = "false";
	params.quality              = "high";
	params.allowFullScreen      = "true";
	params.base				    = ".";
	params.salign	   		    = "tl";
	params.scale 			    = "default";
	params.wmode	   	        = "transparent";
	
	attributes.allowFullScreen  = "true";
	attributes.id			    = "flash_" + vUrl;
	attributes.bgcolor 	  	    = "#000000";
	attributes.wmode	   	    = "transparent";
	
	flashvars.vUrl = "/videos/"+vUrl+".flv";
	flashvars.vName = vName;
	flashvars.vImage = "/images/videos/"+vUrl+".jpg";
	if (vDisable == true) {
		flashvars.vDisable = vDisable;
	}
	
	swfobject.embedSWF("/swf/video-player.swf", "video-player-flash", vWidth, vHeight, "8.0.0", "swf/expressinstall.swf", flashvars, params, attributes);    
	swfobject.createCSS("#"+attributes.id,"outline:none"); 
}

embedVideoWide = function(vUrl, vWidth, vHeight, vName) {
	var params     = {};
	var flashvars  = {};
	var attributes = {};
	
	params.menu                 = "false";
	params.quality              = "high";
	params.allowFullScreen      = "true";
	params.base				    = ".";
	params.salign	   		    = "tl";
	params.scale 			    = "default";
	params.wmode	   	        = "transparent";
	
	attributes.allowFullScreen  = "true";
	attributes.id			    = "flash_" + vUrl;
	attributes.bgcolor 	  	    = "#000000";
	attributes.wmode	   	    = "transparent";
	
	flashvars.vUrl = "/videos/"+vUrl+".flv";
	flashvars.vName = vName;
	
	swfobject.embedSWF("/swf/video-player.swf", "video-player-flash", vWidth, vHeight, "8.0.0", "swf/expressinstall.swf", flashvars, params, attributes);    
	swfobject.createCSS("#"+attributes.id,"outline:none"); 
}

// Required for ie6
sfHover = function() {

    $("#nav li").mouseover(function() {
        $(this).attr("class", $(this).attr("class") + " sfhover");
    });
    $("#nav li").mouseout(function() {
        $(this).attr("class", $(this).attr("class").replace(new RegExp(" sfhover\\b")));
    });

    $("#keywords li").mouseover(function() {
        $(this).attr("class", $(this).attr("class") + " sfhover");
    });
    $("#keywords li").mouseout(function() {
        $(this).attr("class", $(this).attr("class").replace(new RegExp(" sfhover\\b")));
    });
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

function bookmark(){
	var title = "Type3 : The Interactive Agency";
	var url = "http://www.type3digital.com";
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
	else {
		alert("Sorry! Your browser doesn't support this function. Please bookmark this page manually.");
	}
	if(pageTracker._trackEvent){
		pageTracker._trackEvent('icon', 'click', 'bookmark');
	}
}


function printPage(){
	if (window.print) {
		window.print();  
		window.location.href = window.location.href.replace("?print=true", "");
	} 
	else {
		var WebBrowser = "<object id=\"WebBrowser1\" width=\"0\" height=\"0\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\"></object>";
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box WebBrowser1.outerHTML = "";  
	}
	if(pageTracker._trackEvent){
		pageTracker._trackEvent('icon', 'click', 'print');
	}
}

setupCallbackForm = function() {
    $('.talk-to-us input:text').focus(function() {
	    if( this.value == this.defaultValue ) {
		    this.value = "";
	    }
    }).blur(function() {
	    if( !this.value.length ) {
		    this.value = this.defaultValue;
	    }
    });
	    
	$('.talk-to-us input.email').bind('keypress', function(e) {
	    var code = (e.keyCode ? e.keyCode : e.which);
	    if (code == 13) {
	        submitCallback();
	    }
    });

    $('.talk-to-us a.open').click(function() {
        openCallback();
    }).hover(
		function() {
		    $(this).children('img').attr('src', '/images/get-involved/button-submit-arrow-on.gif');
		},
		function() {
		    $(this).children('img').attr('src', '/images/get-involved/button-submit-arrow.gif');
		}
	);

		$('.talk-to-us input.email').bind('keypress', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            openCallback();
        }
    });

    $('.talk-to-us a.submit').click(function() {
        submitCallback();
    });

    $('.talk-to-us input.company').bind('keypress', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            submitCallback();
        }
    });	
    
}

openCallback = function() {
    $('.talk-to-us a.open').hide('medium');
    $('.talk-to-us .extra-fields').show('medium');
}

submitCallback = function() {
    var txt = $(".talk-to-us input.email").val()
	    + "|" + $(".talk-to-us input.telephone").val()
	    + "|" + $(".talk-to-us input.name").val()
	    + "|" + $(".talk-to-us input.company").val();
	    
	 ajaxRequest("callback", txt, function(result) {
          if (result == "False")
            alert("Please enter a valid email address!");
          else {          
             $(".talk-to-us div.form").hide();
             $(".talk-to-us div.complete").show();
          }
     });
}

setupNewsletterForm = function() {
	
	$('.news-letter input.email').focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
	
//	$('.news-letter a.open').click(function() { 
//		openForm(); 
//	}).hover(
//		function() { 
//			$(this).children('img').attr('src', '/images/get-involved/button-submit-arrow-on.gif');
//		},
//		function() { 
//			$(this).children('img').attr('src', '/images/get-involved/button-submit-arrow.gif');
//		}
//	);
	
//    $('.news-letter input.email').bind('keypress', function(e) {
//	    var code = (e.keyCode ? e.keyCode : e.which);
//	    if (code == 13) {
//	        openForm();
//	    }
//    });	
	
	$('.news-letter a.submit').click(function() { 
		submitForm(); 
	});
	
	$('.news-letter input.email').bind('keypress', function(e) {
	    var code = (e.keyCode ? e.keyCode : e.which);
	    if (code == 13) {
	        submitForm();
	    }
    });	
}

submitForm = function() {

    var txt = $(".news-letter input.email").val();
    ajaxRequest("signup", txt, function(result) {
    if (result == "True") {
            pageTracker._trackPageview('/newsletterSignUp');
            $(".news-letter div.form").hide();
            $(".news-letter div.complete").show();
        }
        else {
            alert("Please enter a valid email address!");
        }
    });
}

setupTweetForm = function() {
	
	$('.tweetform input.email').focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
	
	$('.tweetform input.twitter').focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
	
	$('.tweetform a.submit').click(function() { 
		submitTwit(); 
	});
	
	$('.tweetform input.twitter').bind('keypress', function(e) {
	    var code = (e.keyCode ? e.keyCode : e.which);
	    if (code == 13) {
	        submitTwit();
	    }
    });	
}

submitTwit = function() {

    var email = $(".tweetform input.email").val();
    var twit = $(".tweetform input.twitter").val();
    
    if (email.length <= 0 || email == "Your email address") {
        alert("Please enter a valid email address!");
        return;
    }
    
    if (twit.length <= 0 || twit == "Your twitter name") {
        alert("Please enter a valid twitter name!");
        return;
    }
	    
    ajaxRequest("twit", email + "|" + twit, function(result) {
    if (result == "True") {
            pageTracker._trackPageview('/tweetSignUp');
            $(".tweetform div.form").hide();
            $(".tweetform div.complete").show();
        }
        else {
            alert("Please enter a valid email address!");
        }
    });
}

//openForm = function() {
//	$('.news-letter a.open').hide('medium');
//	$('.get-involved .news-letter .extra-fields').show('medium');
//}

// Call asp.net HttpHandler to process js requests
ajaxRequest = function(query, data, callback) {
    $.ajax({ url: "/json_get.ashx",  
        contentType: "application/json; charset=utf-8",
        data: { qry: query, val: data },
        dataType: "json",
        success: function(json) {
                callback(json);
        }
        //error: function (XMLHttpRequest, textStatus, errorThrown) {
		//	alert('An AJAX error has occurred: ' + errorThrown + '\n' + textStatus + '\n' + XMLHttpRequest);
		//}
    });
}

function showTab(vNum) {
	if (!vNum) { var vNum = 1; }
	$('#tab1').css({ display:"none"});
	$('#tab2').css({ display:"none"});
	$('#tab3').css({ display:"none"});
	$('#tab4').css({ display:"none"});
	$('#tab'+vNum).css({ display:"block"});
	var cssObj = { 'background-color' : '#121212' }
	$('#nTab1 a').css(cssObj);
	$('#nTab2 a').css(cssObj);
	$('#nTab3 a').css(cssObj);
	$('#nTab4 a').css(cssObj);
	cssObj = { 'background-color' : '#252525' }
	$('#nTab'+vNum+' a').css(cssObj);
}

function loadXml(vUrl) {
	$.ajax( {
		type:"GET", url:vUrl, dataType:"xml", success:showXml }
	);
}

function showXml(xData) {
	$(xml).find('video').each(function() {
		var code = $(this).find('code').text(); 
		var thumbsrc = $(this).find('thumb').text(); 
		$('#video-tiles').append("<div class='video'><a onclick='return false;' ><img class='sampleImage' src='" + thumbsrc + "' id='" + code + "' alt='" + code + "' /></a></div>")
		}
	);
}