

/*
	pageActions.js
	Chisano Marketing Group

	Developer: Tyson Willey
	Development Started: 9-11-08

	Built with 
		jQuery - www.jquery.com
		SWFObject - blog.deconcept.com/swfobject/

	All this code should be cleaner and more concise, but I have no time.
	Don't give me a hard time about encapsulation and all that jazz...
*/

var currentForm;
var subLinks;
var historyTracker;
var paneTops = [];

var flashInstalled = FlashDetect.installed;

$(document).ready(init);

function init(){
	historyTracker = new historyHandler();
	subLinks = $("#FooterLinks .Lnks A, #sideBar A");

	loadPageContent();
	$(".bio_button").click(toggleTeamBio);
	$(subLinks).click(subLink_click);
	$(".newsArc_link").click(newsLink_click);
	$(".fileUpload input:file").mouseover(uploadOver);
	$(".fileUpload input:file").mouseout(uploadOut);
	$(".fileUpload INPUT:file").change(displayUploadFile);
	$("#formContainer FORM").submit(submitForms);
	$(".mainNav_link").each(function (){
		if (section.toLowerCase() != this.id.toLowerCase()){
			$(this).mouseover(function (){ $(this).addClass("over") });
			$(this).mouseout(function (){ $(this).removeClass("over") });
			$(this).click(showMainNav);
		}else{
			$(this).unbind("click").click(function (){ return false });
			$(this).addClass("over");
			$(this).css("cursor", "default");
		}
	});
	enableLinks();
	setPageImages();
}

function loadPageContent(){
	var splitHref = location.href.split("/");
	var page_section = splitHref[splitHref.length - 2];
	var hasHash = location.hash.length;	

	if (page_section.toLowerCase() == "news"){

		if (hasHash) {
			var splitHash = location.hash.split("=");
			var dateSplit = splitHash[1].split("-");
			yearNum = dateSplit[0];
			monthNum = dateSplit[1];

			getNews(yearNum, monthNum);
			
		}else{
			getNews();
		}

	}else{
        if (hasHash){
            var page = location.hash.substr(1);		
            if (page != "Contact"){
                getPage(page_section, page);
            }else{
                showContact();
            }
        }else{		
            getPage(page_section);
        }
	}
}

function enableLinks (){	
	$("#ContactUsLnk").click(toggleContact);
	$("#ContactUSBtmLnk").click(showContact);	
	$("#locations .tabs A").click(changeTab);
	$("#formSelect A").click(changeForm);
}

function disableLinks (){
	$("#ContactUsLnk").unbind("click").click(deadLink);		
	$("#ContactUSBtmLnk").unbind("click").click(deadLink);	
	$("#locations .tabs A").unbind("click").click(deadLink);
	$("#formSelect A").unbind("click").click(deadLink);
}

function deadLink (){	
	return false;
}


// Show Main Nav
function showMainNav(){
	hideContact();
	var section = $(this).attr("id");

	$(".mainNav_link").removeClass("currentLNK");
	$(this).addClass("currentLNK");

	if (section == "internet"){
		var portImg = path+"images/flash_portPreviews/internet/"+int_imgs[int_port_index];
		var portType = "Interactive";
		int_port_index = (int_port_index + 1 == int_imgs.length) ? 0 : int_port_index + 1;
	}else{
		var portImg = path+"images/flash_portPreviews/traditional/"+trad_imgs[trad_port_index];
		var portType = "Traditional";
		trad_port_index = (trad_port_index + 1 == trad_imgs.length) ? 0 : trad_port_index + 1;
	}

	if (flashInstalled) {
		$("#mainNav_flash").css("height", "260px");
	}else {
		$("#mainNav_flash").css("height", "50px");
	}

	$("#mainNav_flash").slideDown("fast", function (){
		if (flashInstalled){
			var navFlash = new SWFObject(path+"flash/nav.swf", "mainNav_flash_obj", "912", "260", '8', '', false);
			navFlash.addParam("wmode", "transparent");
			navFlash.addParam("showmenu", "false");
			navFlash.addParam("path", path);
			navFlash.addVariable("xmlPath", path+"xml/"+section+"_nav.xml");
			navFlash.addVariable("portXML", path+"xml/portfolio_links.xml");	
			navFlash.write("mainNav_flash");
		}else{
			$("#mainNav_flash H4").hide();
			$("#mainNav_flash H4#mainNav_" + section).fadeIn("fast");
		}
	});

	

	return false;
}

function hideMainNav(){
	$("#mainNav_flash H4").hide();
	$(".mainNav_link").removeClass("currentLNK");
	$("#mainNav_flash").slideUp("fast");
}

function toggleContact(){
	if ($("#contactForm").css("display") == "none"){
		showContact();
	}else{
		hideContact();
	}
	return false;
}


function showContact(form, jobID){

	if (form != undefined){
		currentForm = $("#"+form+"_form");
		var selectedButton = $("#formSelect A[href='#"+form+"']");
		var index = $("#formSelect A").index($("A[href='#"+form+"']"));
		var arrowX = 220 * index + 10;
	}else{
		currentForm = $("#formContainer FORM:first");
		var selectedButton = $("#formSelect A:first");		
		var form = $(selectedButton).attr("href").substr(1);
		var arrowX = 10;
	}	

	var jID = (jobID != undefined) ? jobID : 0;

	if ($("#contactForm").css("display") == "none"){	
		hideMainNav();
		$(".fileUpload").hide();
		$("#ContactUsLnk").addClass("open");
		$("#ContactUsLnk").html("close");
		$("#BrandingWrapper").animate({"marginTop": "+=290px"}, "fast");
		$("#formContainer FORM").hide();
		$(currentForm).show();
		$("#formArrows").css({marginLeft: arrowX});
		$("#formSelect A").removeClass("selected");
		$(selectedButton).addClass("selected");
		$("#contactForm").slideDown("fast", function (){
			$(".fade_container", this).fadeIn("fast", function (){
				$(".fileUpload", this).fadeIn("fast", function(){
					$("INPUT", this).css("marginTop", "0px");
				});
			});			
		});
		if (form == "employment") $(":hidden[name='jobID']", currentForm).val(jID);
		scroll(0, 0);
	}else{
		changeForm(form);
	}
	
	return false;

}

function hideContact(){
	$("#contactForm .fade_container").hide();
	$("#contactForm .fade_container INPUT[type='file']").css("marginTop", "-100px");
	$("#message").hide();
	if ($("#contactForm").css("display") != "none") $("#BrandingWrapper").animate({"marginTop": "-=290px"}, "fast");
	$("#contactForm").slideUp("fast");
	$("#contactForm :input:not(:button)").val("");
	$("#ContactUsLnk").removeClass("open");
	$("#ContactUsLnk").html("contact us");

	scroll(0, 0);
	return false;
}




// Tabs 
function changeTab (){

	var tabName = $(this).attr("href").substr(1) + "_content";
	$("#locations .tabs A").removeClass("active");
	$(this).addClass("active");

	$("#locations .tab_content DIV").removeClass("active");
	$("#locations .tab_content #"+tabName).addClass("active");

	return false;

}


// Set Page Images
function setPageImages (){
	var id = $(".pageImage").attr("id"); 

	$(".pageImage").html("<img src='"+path+"images/pageImages/"+id+".jpg' />");	
	if (id == "ban_Home"){
		var ban_flash = new SWFObject(path+"flash/homepage_anim.swf", "banner_flash_obj", "540", "288", '8', '', false);
		ban_flash.addParam("wmode", "transparent");
		ban_flash.write(id);
	}
}

// Change Form 
function changeForm(form){

	scroll(0, 0);

	if (form != undefined && typeof form == "string"){
		var formToShow = "#"+form;
		var selectedButton = $("#formSelect A[href='#"+form+"']");
	}else{
		var formToShow = $(this).attr('href');
		var selectedButton = $(this);
	}

	disableLinks();

	var par = $("#formSelect");
	var index = $("#formSelect A").index($(selectedButton));
	var arrowX = 220 * index + 10;	

	$("#formSelect A").removeClass("selected");
	$(selectedButton).addClass("selected");
	
	$("#formContainer INPUT[type='file']").css("marginTop", "-100px");
	$("#formContainer .fileUpload").hide();
	$("#formContainer FORM").fadeOut("fast");
	$("#message").fadeOut("fast");	
	

	$("#formArrows").fadeOut("fast", function (){
		$(this).css({marginLeft: arrowX});
		$(this).fadeIn("fast");		
		currentForm = $(formToShow+"_form");
		$(":input:not(:button)", currentForm).val("");
		$(".error").removeClass("error");
		$("LABEL[title]", currentForm).each(function(){
			$(this).html($(this).attr("title"));	
		});
		$("input:file", currentForm).parent().siblings(".uploadText").html("");

		$(currentForm).fadeIn("fast", function(){
			$(".fileUpload", this).fadeIn('fast', function (){
				$("INPUT[type='file']", this).css("marginTop", "0px");
			});
			enableLinks();			
		});

	});

	return false;
}



function uploadOver (){
	$(this).parent().css({backgroundPosition: "0 -13px"});
}

function uploadOut (){
	$(this).parent().css({backgroundPosition: "0 0"});
}

function displayUploadFile (){
	$(this).parent().siblings(".uploadText").removeClass("error");
	var splitVal = $(this).val().split("\\");
	var fileName = splitVal[splitVal.length - 1];
	if (fileName.length >= 20) fileName = fileName.substr(0, 13) + "...";
	var uploadText = $(this).parent().siblings(".uploadText").html(fileName);	
}

// Submit Forms 
function submitForms (){
	var errors = [];
	var values = {};
	
	$(".error").removeClass("error");

	$(":input:not(:button), :hidden", currentForm).each(function (){
		
		// validate email
		if (this.className == "email" && !validateEmail($(this).val())) errors.push({field: $(this), message: "invalid email"});
		
		// check required fields
		if ($(this).attr("name") != "howHear" && $(this).attr("name") != "jobID" && $(this).attr("name") != "doc" && $(this).val() == "" )  errors.push({field: $(this), message: $(this).attr("name") + " required"});
	

		// check uploaded file extension
		if ($(this).attr("name") == "doc" && $(this).val() != ""){
			var splitVal = $(this).val().split(".");
			var extension = splitVal[splitVal.length - 1];
			if (extension != "doc" && extension != "pdf") errors.push({field: $(this), message: "must be .doc or .pdf"});
		}	

		values[$(this).attr("name")] = $(this).val();

		var labelText = $(this).siblings("LABEL").attr("title");
		$(this).siblings("LABEL[title]").html(labelText);

	});

	if (errors.length){ // Display Errors
		
		for(var i = 0; i < errors.length; i++){
			var field = $(errors[i].field);
			var message = errors[i].message;

			if ($(field).attr("name") == "doc") {
				$(field).parent().siblings(".uploadText").addClass("error");
				$(field).parent().siblings(".uploadText").html(message);
			}else if ($(field).attr("name") == "email"){
				$(field).siblings("LABEL").addClass("error");
				$(field).siblings("LABEL").html(message);
			}else{
				$(field).siblings("LABEL").addClass("error");
				$(field).siblings("LABEL").html(message);
			}
		}

		return false;
	}
	
	var formAction = path+"formProcesses/"+$(currentForm).attr("id")+".cfm";
	var formTarget = "formProcessor";
	var encType = "multipart/form-data";
	var method = "post";
	
	$("BODY").append('<div style="display: none" id="processFrame"><iframe name="formProcessor"></iframe></div>');
	$(currentForm).attr("action", path+"formProcesses/"+this.id+".cfm");
	$(currentForm).attr("target", formTarget);
	$(currentForm).attr("enctype", encType);
	$(currentForm).attr("method", method);

	showLoader();
	
	return true;
}

function validateEmail(val){
	var emailRegEx = new RegExp(/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/);
	return emailRegEx.test(val);
}

function showLoader(){
	disableLinks();
	$(currentForm).fadeOut("fast", function (){
		$("#loader").fadeIn("fast");
	});
}

function formSuccess(message) {

	message += "<a class='messageClose' href='#'>close</a>";	
	$("#processFrame").remove();
	$("#message").html(message);
	$("#message A.messageClose").click(hideContact);
	$("#loader").fadeOut("fast", function (){
		$("#message").fadeIn("fast");
	});	
	enableLinks();	
}




// =======================================================
// Handle sub/footer links ///////////////////////////////////////////////////////////////
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


function subLink_click (){
	var href = $(this).attr("href");
	var splitVal = href.split("/");
	var link_section = splitVal[splitVal.length - 2]; 
	var link_page = splitVal[splitVal.length - 1].substr(1);

	if (link_section == section){ // load page with ajax 
		
		// Change Page
		getPage(link_section, link_page);

	}else{ // load new page		
		location.href = href;
	}	
	scroll(0,0);
	return true;
}

function newsLink_click (){
	var href = $(this).attr("href");
	var splitVal = href.split("=");

	var splitDate = splitVal[1].split("-");
	var yearNum = splitDate[0];
	var monthNum = splitDate[1];
		
	// Change Page
	getNews(yearNum, monthNum);
	
	scroll(0,0);
	return true;
}

function getNews(y, m){

	// Reset all highlighted links
	$(subLinks).removeClass("CurrntLnk");

	// Highlight appropriate links
	//$("#article_"+id, subLinks).addClass("CurrntLnk");

	$("#pageCopyPad").fadeOut("fast", function (){
		$("#copyLoader").fadeIn("fast", function (){			

			if (y != undefined && m != undefined){
				var page_path = path+"includes/content/ajax/getArticle.cfm?y="+y+"&m="+m;
			}else{
				var page_path = path+"includes/content/ajax/getArticle.cfm";
			}

			$("#copyContainer").load(page_path, {}, function (){
				$("#copyLoader").fadeOut("fast", function (){
					$("#pageCopyPad").fadeIn("fast");
					$(".expand_button").click(toggleTeamBio);

					$(".expandable_panel").each(function (){
						paneTops.push($(this).y());
					});
				});			
			});
		});
	});
}



function getPage(section, page, type){

	// Reset all highlighted links
	$(subLinks).removeClass("CurrntLnk");

	// Highlight appropriate links
	$(subLinks).each(function (){		
		var hrefSplit = $(this).attr("href").split("#");
		var pageName = hrefSplit[1];

		if (page != undefined){	
			if (page == pageName) $(this).addClass("CurrntLnk");
		}
	});

	$("#pageCopyPad").fadeOut("fast", function (){
		$("#copyLoader").fadeIn("fast", function (){
			if (page != undefined){
				var page_path = path+"includes/content/"+section+"/"+page+".cfm";
			}else{
				var page_path = path+"includes/content/"+section+".cfm";
			}

			$("#copyContainer").load(page_path, {}, function (){				
				$("#copyLoader").fadeOut("fast", function (){
					//alert(this);
					$("#pageCopyPad").fadeIn("fast");
					$(".expand_button").click(toggleTeamBio);					
					$(".contactLink_body").click(toggleContact);
					$(".showEmployment_link").click(showEmployment_contact);
					$("#login_form").submit(submitVidForm);
					$(".expandable_panel").each(function (){
						paneTops.push($(this).y());
					});
				});			
			});
		});
	});
}


// History Tracker (www.unfocus.com)
function historyHandler (){
	var stateVar = "";
	var page_section = "";
	
	this.historyListener = function(historyHash) {
		stateVar = historyHash;
		var splitURL = location.href.split("/");
		page_section = splitURL[splitURL.length - 2];
		getPage(page_section, stateVar);
	};
	unFocus.History.addEventListener('historyChange', this.historyListener);
}



// Toggle Team Bio 
function toggleTeamBio (){
	var container = $(this).parent();
	var containerIndex = $(".content").index($(container));

	$.scrollTo(paneTops[containerIndex]-20, 500, {onAfter: function (){
		
		$(".content").each(function (){
			var tempIndex = $(".content").index(this);
			if (tempIndex != containerIndex){
				collapseBio($(this));
			}
		});
	
		if ($(".collapsed", container).css("display") == "block") {
			expandBio($(container));
		}else{		
			collapseBio($(container));
		}
	
	}});

	

	return false;
}

function collapseBio(tar){	
	$(".apply_button", tar).fadeOut("fast");
	$(".expand_button", tar).html("learn more");
	$(".expanded", tar).slideUp(1000, function (){
		$(".collapsed", tar).fadeIn("fast");
	});
	
	
}

function expandBio(tar){	
	var containerIndex = $(".content").index($(tar));

	$(".apply_button", tar).fadeIn("fast");

	$(".expand_button", tar).html("close");
	$(".collapsed", tar).fadeOut("fast", function (){
		$(".expanded", tar).slideDown(500);
	});
	
}


// Expand Contact Panel defaulted to Employment
function showEmployment_contact (){
	var splitID = this.id.split("_"); 
	var jobID = splitID[1];
	
	showContact("employment", jobID);

	return false;	
}


// Video Conference Login Handling
function submitVidForm(){
	
	var form 		= this;
	var loginID 	= $("#login_id_input", this);
	var password 	= $("#password_input", this);
	var errors 		= [];
	
	$("LABEL", form).removeClass("error");
	$("LABEL", form).each(function (){ $(this).html($(this).attr("title")); });
	
	$("#errorMsg", form).hide();
	
	if (!$(loginID).val().length) errors.push({field:loginID, message:"login id is required."});
	if (!$(password).val().length) errors.push({field:password, message:"password is required."});
	
	if (errors.length){
		for (i in errors){
			var errorLabel = $(errors[i].field).siblings("LABEL");	
			$(errorLabel).css({"display": "none"});
			$(errorLabel).html(errors[i].message);
			$(errorLabel).addClass("error");
			$(errorLabel).fadeIn('fast');
		}
	}else{
		var dataObj = {
			login_id		:	$(loginID).val(), 
			password	:	$(password).val()};
		
		// Submit Form to CFM Script
		$.ajax({
		   type		: 	"GET",
		   url			: 	path+"formProcesses/vidConf_login.cfm",
		   data		: 	dataObj,
		   success	:  	
		   		function(xml){
										
					var status = $("status", xml).text();
					if (status == "success") { 						
						window.location.reload(true); 
					} else { 
						$("#errorMsg", form).html("Your Login Credentials don't match our records.  Please try again.");
						$("#errorMsg", form).slideDown('slow');
					}
					
				}
		 });
	}
	
	return false;
}


