/**
 * common javascript for styleseries microsite
 */

/**
 * The following functions are called from Flash (AnchorSite.swf) 
 * via External Interface (Flash >>> js):
 * 		showInviteForm()
 * 		hideInviteForm()
 * 		trackEvent(String::eventid)
 */  
//called when "invite" tab (in the Flash) is clicked
//and the current location is not already "invite"
function showInviteForm()
{
	resetInviteForm();
	$("#inviteHeader, #inviteHeaderCover").removeClass("invisible");
	$("#inviteWrapper").removeClass("invisible");
}
//called when any tab other than "invite" (in the Flash) is clicked
function hideInviteForm()
{
	$("#inviteHeader, #inviteHeaderCover").addClass("invisible");
	$("#inviteWrapper").addClass("invisible");
}
//called from Flash for any event that somebody wants tracked...
//for DKO WebTrends and SearchRev "search pixels" and SMG Floodlight tags and...
function trackEvent(eventid)
{
	
	try 
	{
		if (eventid)
		{
			//first, call internal (for DKO) WebTrends tracking
			//dcsMultiTrack("DCS.dcssip", DCS.dcssip, "DCS.dcsuri", DCS.dcsuri, "WT.ti", eventid);
			if ( eventid.indexOf("http://") === 0 )
			{
				eventid = eventid.substr(7);
			}
			dcsMultiTrack("DCS.dcssip", DCS.dcssip, "DCS.dcsuri", window.location.pathname+eventid, "WT.ti", eventid);
			
			//following code is for dynaically firing DoubleClick Floodlight tags and SearchRev pixels.
			//these two tags are also coded in HTML on the JSP page
			if ( ! htmlTrackInitialLoad )
			{
				var catID  = null;
				var srPage = null;
				var srAmnt = 0;
				var type   = "dietc255";  //default
				var rndOrd = Math.floor(Math.random()*100000000);
				switch(eventid)
				{
					case 'watch_tab_clicked':         catID = "dietc547"; srAmnt = "1"; srPage = "StyleSeriesWatch";  break; // 1 = watch
					case 'invite_form_initiated':     catID = "dietc339"; srAmnt = "2"; srPage = "StyleSeriesInvite"; break; // 2 = invite
					case 'main_share_button_clicked': catID = "style037"; srAmnt = "3"; srPage = "StyleSeriesShare";  break; // 3 = share
					case 'invite_email_sent':         catID = "style974"; break; // 4 = invite success
					case 'more_panel_opened':         catID = "dietc724"; break; // 5 = more		
				}	
				
				if (catID)
				{	
					floodlightTag = "http://fls.doubleclick.net/activityi;src=1352258;type=" + type + ";cat=" + 
										catID + ";ord=" + rndOrd + "?";
					
					var flDiv = document.getElementById("DCLK_FLDiv");
					if ( ! flDiv )
					{
						flDiv = document.body.appendChild(document.createElement("div"));
						flDiv.setAttribute("id","DCLK_FLDiv");
						flDiv.style.position = "absolute";
						flDiv.style.visibility = "hidden";
						flDiv.style.top = "0px";
					}
					var iFrameHTML = '<iframe id="DCLK_FLIframe" src="' + floodlightTag + '"></iframe>';
					flDiv.innerHTML = iFrameHTML;
					//alert ("iFrameHTML = " + iFrameHTML); //uncomment if needed for local testing
				}	
				
				if (srPage)
				{
					var searchRevTag = new Image();
					searchRevTag.src = "http://s1.srtk.net/www/delivery/ti.php?trackerid=517&cb=42229&_sr_amount=" + 
							srAmnt + "&_sr_page=" + srPage + "&ord=" + rndOrd;
				}
			}
		}
	}
	catch(err0) {}
	
	htmlTrackInitialLoad = false;
	
	try
	{
		if ( console )
		{
			console.log("EVENT:=" + eventid);
		}
	}
	catch(err1) {}
}

/**
 * The following functions call exposed methods withing the Flash (AnchorSite.swf) 
 * via External Interface (js >>> Flash):
 * 		doneInviteForm() ===>>> endInviteForm()
 */  
//goes back to "main" panel in anchor site Flash
function doneInviteForm()
{
	$("#ssAnchorFlash").get(0).endInviteForm();
}



function resetInviteForm()
{
	resetCaptcha("kocaptcha");
	$("#errorMessageText").addClass("invisible");
	$("#inviteForm label").removeClass("error");
	$("#inviteForm input:text").val("");
	$("#cbPermission").get(0).checked = false;
	
	$("#invitePanel, #inviteHeader, #inviteHeaderCover").css("display", "block");
	$("#inviteConfirmation, #inviteConfirmation div").css("display", "none");
}

function showInviteConfirmation(bSuccess)
{
	var confirmResult = (bSuccess ? "Success" : "Failed");
	$("#invitePanel, #inviteHeader, #inviteHeaderCover").css("display", "none");
	$("#inviteConfirmation div").css("display", "none");
	$("#inviteConfirmation, #inviteConfirmation" + confirmResult).css("display", "block");
}

function resetCaptcha(id)
{
	$("#" + id).attr("src", "/styleseries/inc/kocaptcha.jsp?rnd=" + Math.random());
}

function captchaCodeError(text)
{
	return (getFile("/styleseries/check-captcha.jsp?capcheck=" + text) != "true");
}

function getFile(url) 
{
	if (window.XMLHttpRequest) {
		AJAX=new XMLHttpRequest();
	} else {
		AJAX=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (AJAX) {
		AJAX.open("GET", url, false);
		AJAX.send(null);
		return AJAX.responseText;
	} else {
		return false;  
	}
}

function processInviteForm()
{
	$("#errorMessageText").addClass("invisible");
	$("#inviteForm label").removeClass("error");
	var validEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var thisFieldHasError = null;
	var formHasErrors = false;
	$("#inviteForm input").each(function()
	{
		thisFieldHasError = false;
		if (this.type == "text")
		{
			this.value = $.trim(this.value);
			if (this.value === "")
			{
				thisFieldHasError = true;
			}
			else if ($(this).hasClass("email"))
			{
				thisFieldHasError = ! validEmail.test(this.value);
			}
			else if ($(this).hasClass("captcha"))
			{
				thisFieldHasError = captchaCodeError(this.value);
				if (thisFieldHasError)
				{
					resetCaptcha("kocaptcha");
				}
			}
		}
		else if (this.id == "cbPermission" && this.checked === false)
		{
			thisFieldHasError = true;
		}
		if (thisFieldHasError)
		{
			$("label[for=" + this.id + "]").addClass("error");
			formHasErrors = true;
		}
	});
	
	if (formHasErrors)
	{
		$("#errorMessageText").removeClass("invisible");
	}
	else
	{
		var yourEmail = $("#yourEmailTextBox").val();
		var friendEmail = $("#friendEmailTextBox").val();
		var pinCode = $("#pinCode").val();
		var securityCode = $("#securityCodeTextBox").val();
		var processUrl = "/styleseries/inviteProcess.jsp?youremail=" + yourEmail + "&friendemail=" + 
								friendEmail + "&pincode=" + pinCode + "&captcha=" + securityCode;
		//var processUrl = "/styleseries/inviteProcess.jsp?youremail=" + yourEmail + "&friendemail=" + friendEmail + "&pincode=" + pinCode;
		var processResult = $.trim(getFile(processUrl));
		$("#confirmFriendEmail").html($("#friendEmailTextBox").val());
		showInviteConfirmation(processResult=="true");
		if (processResult=="true")
		{
			trackEvent("invite_email_sent");
		}
	}
}

var nextBgcolor = "#ccc";
var nextBgnumbr = 10;
function resetBackground(selector)
{
	$(selector).each(function()
	{
		//$(this).css("backgroundImage", "url(/styleseries/img/clear.gif?rnd=" + Math.random() + ")");
		//var nextBgcolor = $(this).css("backgroundColor");
		nextBgnumbr++;
		nextBgnumbr = ((nextBgnumbr > 9) ? 0 : nextBgnumbr);
		nextBgcolor = "#ccccc" + nextBgnumbr;
		//trackEvent("nextBgcolor = " + nextBgcolor);
		$(this).css("backgroundColor", nextBgcolor);
	});
}



//execute functions to initialize page when DOM is ready
jQuery(document).ready(function()
{
	//====================================
	//=== BEGIN events for 'testpanel' ===
	$("#ctl1").click(function()
	{
		$("#inviteHeader, #inviteHeaderCover").toggleClass("invisible");
		$("#inviteWrapper").toggleClass("invisible");
	});
	$("#ctl2").click(function()
	{
		$("#inviteHeader, #inviteHeaderCover").addClass("invisible");
		$("#inviteWrapper").addClass("invisible");
		doneInviteForm();
	});
	$("#ctl3").click(function()
	{
		resetBackground("body");
	});
	//=== E=N=D events for 'testpanel' ===
	//====================================


	//===========================================
	//=== BEGIN events for form parts & links ===
	$("#btnSendEmail").click(function(event)
	{
		processInviteForm();
		event.preventDefault();
	});
	$("#securityCodeReload").click(function()
	{
		resetCaptcha("kocaptcha");
	});
	$("#inviteConfirmationSuccess a").click(function(event)
	{
		showInviteForm();
		event.preventDefault();
	});
	//=== E=N=D events for form parts & links ===
	//===========================================
	

	var navUserAgent = navigator.userAgent.toLowerCase();
	if (navUserAgent.indexOf("msie 6.") > -1 || navUserAgent.indexOf("safari") > -1)
	{
		//console.init();
		$(window).resize(function()
		{
			var cssHeight = (document.body.clientHeight <= 600 ? "600px" : "100%");
			if ( $("#content").css("height") != cssHeight )
			{
				//console.log(document.body.clientHeight + "change height to " + cssHeight);
				$("#content").css("height", cssHeight);
			}
		});
		var cssHeight = (document.body.clientHeight <= 600 ? "600px" : "100%");
		$("#content").css("height", cssHeight); 
	}
	
	var needMacFix = (navigator.platform.toLowerCase().indexOf("mac") === 0);
	if (needMacFix) 
	{
		$("#inviteWrapper").addClass("macfixWrapper");
		$("#permissionText input").change(function(){resetBackground("body");});
		$("#kocaptcha").load(function(){resetBackground("body");});
		$("#btnSendEmail").click(function(){resetBackground("body");});
		
		$("#inviteWrapper, #inviteHeaderCover").bind("mouseup mouseover mouseout", function(){resetBackground("body");});
		$("#inviteWrapper input:text").bind("focus blur", function(){resetBackground("body");});
		$("#content, #permissionText input, #permissionText a, #permissionText label, #footerLegal a").bind(
				"mouseover mouseout", function(){resetBackground("body");});
	}

});
$(window).load( function()
{
	window.htmlTrackInitialLoad = false;
});
