/// <reference path="intellisense/jquery.intellisense.js" />
/// <reference path="intellisense/jquery.ajaxdotnet.intellisense.js" />

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function latinCharSet() {
    var isLatin = true;
    if (window.location.hostname.indexOf("chs") > -1)
        isLatin = false;
    if (window.location.hostname.indexOf("cht") > -1)
        isLatin = false;
    if (window.location.hostname.indexOf("ru-ru") > -1)
        isLatin = false;
    if (window.location.hostname.indexOf("kr-kr") > -1)
        isLatin = false;
    if (window.location.hostname.indexOf("jp-jp") > -1)
        isLatin = false;
    if (window.location.hostname.indexOf("gr-gr") > -1)
        isLatin = false;

    if (!isLatin) {
        //parseFragments();
    }

    return isLatin;
}

function getLatin() {
    if (!latinCharSet())
        return "_sf";
    return "";
}

var fragmentsParsed = false;

function cufonReplace() {
    if (latinCharSet()) {
        Cufon.replace(".cuf-helv", { fontFamily:'helvetica', hover:true });
		Cufon.replace(".cuf-futu", { fontFamily:'futura', hover:true });
		Cufon.replace(".cuf-joba", { fontFamily:'johnbaskerville', hover:true });
    }
    else {
        if (!fragmentsParsed) { parseFragments(); }
        Cufon.replace(".cuf-helv span.cuf-helv", { fontFamily: 'helvetica', hover: true, hoverables: {a:true , span:true} });
        Cufon.replace(".cuf-futu span.cuf-futu", { fontFamily: 'futura', hover: true, hoverables: { a: true, span: true} });
        Cufon.replace(".cuf-joba span.cuf-joba", { fontFamily: 'johnbaskerville', hover: true, hoverables: { a: true, span: true} });
		fragmentsParsed = true;
    }
}

var runCount = 0;

function parseFragments() {
    if (runCount < 1) {
        parseElements(".cuf-helv");
        parseElements(".cuf-joba");
        parseElements(".cuf-futu");
        runCount++;
    }
}

function parseElements(cufClass) {
    var elements = $(cufClass)
    var i = 0;
    for (i = 0; i < elements.length; i++) {
        
        var elem  = elements[i];
        
        var subject = $(elem).html();

        var newClass = cufClass.toString().replace("#mainColumn ", "");

        var updatedContents = subject.toString().replace(/([a-z|A-Z|0-9|\ ]+)/g, "<span class=\"" + newClass.substr(1, cufClass.toString().length -1) + "\">$1</span>");

        $(elem).html(updatedContents);
    }
}

function showTermsAndConditions()
{
	window.open
	(	
		'/terms-and-conditions.aspx',
		//'Terms and Conditions',
		'_blank',
		'width=420,height=600,menubar=no,status=no,location=no,toolbar=no,scrollbars=yes'		
	);
}

function showPrivacyPolicy()
{
	window.open
	(	
		'/privacy-policy.aspx',
		//'Privacy Policy',
		'_blank',
		'width=420,height=600,menubar=no,status=no,location=no,toolbar=no,scrollbars=yes'		
	);
}

function closeOverlay(callback)
{
	$("#overlay").empty();
	$("#overlayWrapper").dialog("close");
	showHideOverlayShade();
	if (callback) callback.call();
}

function openOverlayFlash(callbackName)
{
	window.eval(callbackName + '()');
	showHideOverlayShade("show");
	$("#overlayWrapper").dialog("open");
	$("#overlayWrapper").css("display", "block");
	return true;
}

function openOverlayWithParam(executable)
{
	window.eval(executable);
	showHideOverlayShade("show");
	$("#overlayWrapper").dialog("open");
	$("#overlayWrapper").css("display", "block");
	return true;
}

function bindMenuEvents()
{
	$("#myjquerymenu li").mouseover(function(){
		openOverlay(function(){});
	});
	
	$("#myjquerymenu li").mouseout(function(){
		closeOverlay(closeOverlayCallback);
	});
	
	$("ul.secondLevel").mouseout(function(){
		closeOverlay(closeOverlayCallback);
	});
	
	
	/*$(".topLevel li").mouseover(function(item){
		if ($(this).children().length > 1) {
			showSubMenu(this.lastChild.firstChild.id);
		}
	});
	$(".topLevel li").mouseout(function(item){
		if ($(this).children().length > 1) {
			hideSubMenu($("#"+this.lastChild.firstChild.id));
		}
	});
	$("ul.secondLevel").mouseout(function(){
		hideSubMenu(this);
	}); */
}

function showSubMenu(subMenu)
{
	var menuElement = $("#" + subMenu);
	menuElement.show();
	openOverlay(function(){});
	return true;
}

function hideSubMenu(subMenu)
{
	$(subMenu).hide();
	closeOverlay(function(){});
	return true;
}

function showHideOverlayShade(action){
	if (action == 'show') {
		$("#flashHolder").css({visibility:'hidden'}).find('embed').hide();
		$("#flashHolder").css({height:'0'});
		$("#flashHolder").css("min-height", "0");
		$("#backgroundFlashHolder").show();
	}
	else {
		$("#flashHolder").css({height:'90%'});
		$("#flashHolder").css("min-height","598px");
		$("#flashHolder").css({visibility:'visible'}).find('embed').show();
		$("#backgroundFlashHolder").hide();
	}
}

function openOverlay(callback)
{
	callback.call();
	$("#overlayWrapper").dialog("open");
	$("#overlayWrapper").css("display", "block");
}

function buildOverlay(viewportheight, viewportwidth, opacityValue)
{
	if (opacityValue == undefined)
	{
		opacityValue = 0.0;
	}

	//Instantiate dialog
    $("#overlayWrapper").dialog({
        modal: true,
        autoOpen: false,
        height: viewportheight,
        width: viewportwidth,
        position: 'center',
        resizable: false,
        draggable: false,
        overlay: { 
            opacity: opacityValue, 
            background: "black" 
        },
        dialogClass: 'regDialog'
    });
    $(".ui-dialog-overlay").css("height", viewportheight + "px");
}

function getViewportHeight()
{
	var height;
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined')
	{
		height = window.innerHeight;
	}
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined'
		&& typeof document.documentElement.clientWidth !=
		'undefined' && document.documentElement.clientWidth != 0)
	{
		height = document.documentElement.clientHeight;
	}
	// older versions of IE
	else
	{
		height = document.getElementsByTagName('body')[0].clientHeight;
	}
	return height;
}

function getViewportWidth()
{
	var width;
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined')
	{
		width = window.innerWidth;
	}
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined'
		&& typeof document.documentElement.clientWidth !=
		'undefined' && document.documentElement.clientWidth != 0)
	{
		width = document.documentElement.clientWidth;
	}
	// older versions of IE
	else
	{
		width = document.getElementsByTagName('body')[0].clientWidth;
	}
	
	return width;
}

function buildContactUsForm()
{
	//load form through AJAX
	$("#overlay").load("/membership/contact-us.aspx #dialogHolder",null, function(responseText, textStatus, XMLHttpRequest){
		//prepare validation
		buildContactUsValidator();
	});
}

function buildContactUsMoPForm()
{
	//load form through AJAX
	$("#overlay").load("masters-of-photography/contact-us.aspx #dialogHolder",null, function(responseText, textStatus, XMLHttpRequest){
		//prepare validation
		buildContactUsMoPValidator();
	});
}

function buildContactUsValidator()
{
	$("#loginForm").validate({
		onfocusout:false,
		onkeyup:false,
		onsubmit:false,
		errorclass: "error",
		errorElement: "span",
		errorLabelContainer:"#summary",
		wrapper:"li",
		showErrors: function(errorMap, errorList){
				$("#summaryBlock").show();
				this.defaultShowErrors();
		},
		rules: {
			confirmEmail: {
				equalTo: "#m_email"
			}
		},
		messages:{
			email: $("#emailMessage").val(),
			confirmEmail: $("#confirmEmailMessage").val(),
			message : $("#messageMessage").val()
		}
	});
}

function buildContactUsMoPValidator()
{
	$("#loginForm").validate({
		onfocusout:false,
		onkeyup:false,
		onsubmit:false,
		errorclass: "error",
		errorElement: "span",
		errorLabelContainer:"#summary",
		wrapper:"li",
		showErrors: function(errorMap, errorList){
				$("#summaryBlock").show();
				this.defaultShowErrors();
		},
		rules: {
			confirmEmail: {
				equalTo: "#m_email"
			}
		},
		messages:{
			email: $("#emailMessage").val(),
			confirmEmail: $("#confirmEmailMessage").val(),
			message : $("#messageMessage").val(),
			firstName : $("#firstNameMessage").val(),
			lastName : $("#lastNameMessage").val(),
			bottleCode : $("#bottleCodeMessage").val(),
			bottlePurchaseLoc : $("#bottlePurchaseLocMessage").val()
		}
	});
}

function submitContactUsForm()
{
	if ($("#loginForm").valid())
	{
		$("#summaryBlock").hide();
		beginContactUsCall();
	}
}

function submitContactUsMoPForm()
{
	if ($("#loginForm").valid())
	{
		$("#summaryBlock").hide();
		beginContactUsMoPCall();
	}
}

function beginContactUsCall()
{
	makeServiceCall(
		$("#loginForm"),
		"/services/loginservice.asmx/ContactUs",
		{
			email : $("#m_email").val(),
			message : $("#m_message").val()
		},
		function(obj){ 
			contactUsCallBackComplete(obj);
		},
		function(obj){
			contactUsCallBackComplete(obj);
		}
	);
}

function beginContactUsMoPCall()
{
	makeServiceCall(
		$("#loginForm"),
		"/services/loginservice.asmx/ContactUsMoP",
		{
			email : $("#m_email").val(),
			message : $("#m_message").val(),
			firstName : $("#m_firstName").val(),
			lastName : $("#m_lastName").val(),
			bottleCode : $("#m_bottleCode").val(),
			bottlePurchaseLoc : $("#m_bottlePurchaseLoc").val(),
			dob : readLinked()
		},
		function(obj){ 
			contactUsCallBackComplete(obj);
		},
		function(obj){
			contactUsCallBackComplete(obj);
		}
	);
}

function contactUsCallBackComplete(obj)
{
	var status = obj.d;
	
	//hide spinner
	$("#m_spinner").hide();
	
	if (status == '##Success##')
	{
		//hide form
		$("#loginForm fieldset").hide();
		$("#buttons").hide();

		//hide copy except for title
		$("#copy p").hide();
		
		//show success div
		$("#feedback").show();
		
	}
	else 
	{
		$("#loginForm input").attr("disabled", "");
		$("#loginForm select").attr("disabled", "");
		
		$("#summaryBlock").show();
		
		$("#errorSummaryHeader p").html("We were unable to send your message at this time.  Please try again later. Click <a href='#' onclick='closeOverlay(closeOverlayCallback);'>here</a> to return to The Macallan");
		$(".errorSummary").html("");
	}
} 

function bookmarkAddress(url, title)
{
	if(window.external && (!document.createTextNode || (typeof(window.external.AddFavorite)=='unknown')))
	{// IE/Win
		if (url.indexOf('http://') == -1)
		{
			url = 'http://' + url;
		}
		window.external.AddFavorite(url, title); 
	} else {
		prompt('Please use your browser\'s interface to maunally bookmark this address: ',url);
	} 
	return true;
}