﻿/* Kadfire                                  *
 * ---------------------------------------- *
 * scriptoids, functionalisms and javalamps *
 * jared at type3digital                    *
 * last mod 02.12.09                        *
 * ---------------------------------------- */
 
// const
var val_Required_FirstName = "Please enter your first name";
var val_Required_LastName = "Please enter your surname";
var val_Required_Email = "Please enter your email address";
var val_Invalid_Email = "Please enter a valid email address";
var val_Required_Text = "Please enter your enquiry";

// init
$(document).ready(function() {
    initLinks();
    initForms();
	
	if ($("#printerSelector").length){
		initDropDownsMarket();	
	}
        
    if ($("#fEnquiry").length) {
        initEnquiry();
    }
    
    if ($("#fSignup").length) {
        initSignup();
    }
    
    if ($("#related").length) {
        initRelatedProducts();
    }

    if ($(".marketToggler").length) {
        initMarketToggler();
    }

    if ($(".swapImage").length) {
        initImageSwappinator();
    }


    if ($("#ddlFilterManufacturer").length) { initManufacturerSelector(); }
	
	
	if ($('.makeSafe').length) {
		
		$('.makeSafe').each(function(index) {
			var thisHref = $(this).attr('href');	
			thisHref=escape(thisHref);
			$(this).attr('href', thisHref);
		 });
				
	}
	
//	$('.submitDD').click(function(){
//		initDropDownsMarket();
//	});
	
	if ($('.printWidthSelector').length) {
	    selectedFilter = $('.printWidthSelector').val();
	    if (selectedFilter.length > 2) {
		    $('.productListHidden').show();
	    }
	
	}
	
	//tamingselect();
	
	$('.showAllPS').click(function(){
		
				$('.productListHidden').show();
				$('.productListHidden').addClass('showingall');
        $(this).hide();
	 });
		
		$('.tblInks a').attr('href', '#');
});

function initDropDownsMarket() {
	
	$(".fPrintSelectorThing").validate({
        onfocusout: false,
        onkeyup: false,
        errorClass: "invalid",      
        wrapper: "li",
        errorLabelContainer: "#fPrintSelectorThing .messageBox",
        debug: false,
        rules: {
            Print_Market: { required: true }
        },
        messages: {
            Print_Market: { required: "* required" }
        }
    });

    $(".fPrintSelectorThing").submit(function() {

        if (!$(".fPrintSelectorThing").valid()) {
            return false;
        }
        var printMarketSelection = $(".fPrintSelectorThing select[name='Print_Market']").val();

        if (printMarketSelection == "1") {
            printMarketSelection = 'cad-gis';
        }
        if (printMarketSelection == "2") {
            printMarketSelection = 'photography-and-fine-art';
        }
        if (printMarketSelection == "3") {
            printMarketSelection = 'print-for-pay';
        }
        if (printMarketSelection == "4") {
            printMarketSelection = 'production';
        }
        if (printMarketSelection == "5") {
            printMarketSelection = 'poster-and-sign-making';
        }
        
        if (printMarketSelection == "6") {
            printMarketSelection = 'proofing';
        }
        if (printMarketSelection.length > 0) {
            newAction = '/hardware-and-consumables/large-format-printers/' + printMarketSelection + '/';
            $('.fPrintSelectorThing').attr('action', newAction);
        }
    });
}

function initLinks() {

     // target blank
    $(".aBlank").click(function() { 
        // log click to analytics
        var url = this.href;
        url = url.slice(url.lastIndexOf("://") + 3);
        if(typeof(pageTracker) != "undefined")
            pageTracker._trackPageview(location.pathname + "external/" + url);
        // open new window
        window.open(this.href); return false; 
    });
}

function initRelatedProducts() {

    $("#lnkConsumables").click(function() {

        if ($("#related").css("display") == "none") {
            // hide info, show related
            $("#info").fadeOut(500, function() {
                $("#related").fadeIn(500);
                $("#lnkConsumables").children("span").html("Information about <br/>this printer");
            });
        }
        else {
            // hide related, show info
            $("#related").fadeOut(500, function() {
                $("#info").fadeIn(500);
                $("#lnkConsumables").children("span").html("Find consumables for<br />this printer");
            });
        }
    });
    
    $(".relationSelector a").click(function() {
    
        $(".relationSelector a").removeClass("on");
        $(this).addClass("on");
        
        
        var temp = $(this).attr('id');          
        temp = temp.slice(temp.lastIndexOf('_') + 1);
        
        $("#related .table").hide();
        
        $("."+temp).show();
        
    });
}

function initMarketToggler() {

    $(".marketToggler").click(function() {
        $(this).parent().parent().children(".marketProducts").slideToggle("500");
    });
    
    $(".marketInfo .more a").click(function() {
        $(this).parent().parent().parent().children(".marketProducts").slideToggle("500");
    });
}

function initImageSwappinator() {

    $(".swapImage").click(function() {
        var temp = $(this).attr('id');          
        temp = temp.slice(temp.lastIndexOf('_') + 1);
    
        $(".lstSwap").removeClass("on");
        $(this).parent().addClass("on");
        ajaxRequest("loadImage",
            temp,
            function(output) {
                if (output.length) {
                    
                    $("#imgProduct").fadeOut(500, function() {
                        $("#imgProduct").attr("src", output);
                        $("#imgProduct").fadeIn();
                    });
                }
        });
    });

}

// manufacturer drop down list
function initManufacturerSelector() {

    $("#ddlFilterManufacturer").change(function() {
        location.href = $(this).val();
    });
}

// common form configuration
function initForms() {
	
	$(".pnlComplete").hide();
    //custom validation rules - initial value
    $.validator.addMethod("initialValue", 
        function(value, element) {
           return $(element).attr("title") != value;
        }, "Required"
    );
    
    // on focus, clear text
    $(".initial").focus(function() {
        if ($(this).val() == $(this).attr("title"))
            $(this).val("");
    });
    
    // on blur, add default text if empty
    $(".initial").blur(function() {
        if ($(this).val() == "")
            $(this).val($(this).attr("title"));
    });
}

function initSignup() {
    
    $("#btnSignup_Toggle").click(function() {
        $("#fSignup").slideToggle(500);
    });
    
    // validate form
    $("#fSignup").validate({
        onfocusout: false,
        onkeyup: false,
        errorClass: "invalid",      
        wrapper: "li",
        errorLabelContainer: "#fSignup .messageBox",
        debug: false,
        rules: {
            Email: { required: true, email: true, initialValue: true }
        },
        messages: {
            Email: { required: val_Required_Email, email: val_Invalid_Email }
        }
    });
    
    // cancel form bubble for javascript
    $("#fSignup").submit(function() { return false; });
    
    $("#btnSignup_Submit").click(function() {
	    submitSignup();
    });
    
    // enter key
//    $("#txtSignup_Email").bind("keypress", function(e) {
//	    var code = (e.keyCode ? e.keyCode : e.which);
//	    if (code == 13) {
//	        submitSignup();
//	    }
//    });
}

function submitSignup() {
    
    if ($("#fSignup").valid()) {
        var obj = new Object();
        obj.Email = $("#txtSignup_Email").val();

        ajaxRequest("submitSignup",
            JSON.stringify(obj),
            function(output) {
                if (output == true) {

                    // log to google
                    if(typeof(pageTracker) != "undefined")
                        pageTracker._trackPageview(location.pathname + "siguup_submitted/");
                    
                    $("#fSignup").hide();
                    $("#pnlSignupComplete").show();
                   
                }
            });
    }
    
}

function initEnquiry() {
    
    $("#lnkShowEnquiry").click(function() {
        //$("#enquiryForm").slideDown(500);
        showOverlay("#enquiryForm", 210, 200);
    });
    
    $("#btnEnquiry_Cancel").click(function() {
        hideOverlay("#enquiryForm");
    });
    
    // validate form
    $("#fEnquiry").validate({
        onfocusout: false,
        onkeyup: false,
        errorClass: "invalid",      
        wrapper: "li",
        errorLabelContainer: "#fEnquiry .messageBox",
        debug: false,
        rules: {
            FirstName: { required: true, initialValue: true },
            LastName: { required: true, initialValue: true },
            Email: { required: true, email: true, initialValue: true },
            Text: { required: true, initialValue: true }
        },
        messages: {
            FirstName: val_Required_FirstName,
            LastName: val_Required_LastName,
            Email: { required: val_Required_Email, email: val_Invalid_Email },
            Text: val_Required_Text
        }
    });
    
    // cancel form bubble for javascript
    $("#fEnquiry").submit(function() { return false; });
    
    // submit button
    $("#btnEnquiry_Submit").click(function() {
        submitEnquiry();
    });
    
    
    // enter key
    $("#txtEnquiry_Text").bind("keypress", function(e) {
	    var code = (e.keyCode ? e.keyCode : e.which);
	    if (code == 13) {
	        submitEnquiry();
	    }
    });
}

function submitEnquiry() {

    if ($("#fEnquiry").valid()) {
        var obj = new Object();
        obj.FirstName = $("#txtEnquiry_FirstName").val();
        obj.LastName = $("#txtEnquiry_LastName").val();
        obj.Email = $("#txtEnquiry_Email").val();
        obj.Telephone = $("#txtEnquiry_Telephone").val();
        obj.Company = $("#txtEnquiry_Company").val();
        obj.Text = $("#txtEnquiry_Text").val();
        obj.ProductID = parseInt($("#hdnProductID").val(), 10);

        ajaxRequest("submitEnquiry",
            JSON.stringify(obj),
            function(output) {
                if (output == true) {

                    // log to google
                    if(typeof(pageTracker) != "undefined")
                        pageTracker._trackPageview(location.pathname + "enquiry_submitted/");
                    
                    hideOverlay("#enquiryForm");
                }
            });
    }
}

// Call asp.net HttpHandler to process js requests
function ajaxRequest(query, data, callback) {
    $.ajax({ 
        type: "POST",
        url: "/x.processor.ashx",   
        cache: false,
        data: { qry: query, data: data },
        dataType: "json",
        success: function(output) {
                callback(output);
        },
        error: function(xmlhr, status, err){
            console.error(err);
            var response = eval("("+xmlhr.responseText+")");
            console.log(response);
		}
    });
}

// Modal Overlay :
// ---------------
// The Bullen Overlay Protocol Methodology and Technique
// (c) 2009 Chris Bullen Enterprises
//
function showOverlay(obj, leftOffset, topOffset) {
    
    // Get window dimensions and apply to overlay		
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var documentHeight = $(document).height();
	var scrollPosition = $(window).scrollTop();
	var finalHeight = 100;
	
	if (windowHeight >= documentHeight) {			
		finalHeight = windowHeight;
	} else {
		finalHeight = documentHeight;
	}
	
	$("#overlay").css({ height:windowHeight, width:windowWidth, top:scrollPosition, cursor:"pointer" });
	
	var contentLeft = (windowWidth / 2) - leftOffset;
	var contentTop = ((windowHeight / 2) - topOffset) + scrollPosition;	
	
	$(obj).css({ left: contentLeft });	
	
	// Animate overlay in, then fade in content
	$("#overlay").slideDown(500, function() {	
		$(this).height(finalHeight).css({ top:0 });
		$(obj).fadeIn(500);
	});	
}

function hideOverlay(obj) {
    $(obj).fadeOut(500, function() {
        var windowHeight = $(window).height(); $("#overlay").height(windowHeight); $("#overlay").slideUp(250);
    }
   );
}

function tamingselect()
{
	
	return true /*
	if(!document.getElementById && !document.createTextNode){return;}
	
// Classes for the link and the visible dropdown
	var ts_selectclass='turnintodropdown'; 	// class to identify selects
	var ts_listclass='turnintoselect';		// class to identify ULs
	
	var ts_boxclass='dropcontainer'; 		// parent element
	var ts_triggeron='activetrigger'; 		// class for the active trigger link
	var ts_triggeroff='trigger';			// class for the inactive trigger link
	var ts_dropdownclosed='dropdownhidden'; // closed dropdown
	var ts_dropdownopen='dropdownvisible';	// open dropdown
/*
	Turn all selects into DOM dropdowns

	var count=0;
	var toreplace=new Array();
	var sels=document.getElementsByTagName('select');
	for(var i=0;i<sels.length;i++){
		if (ts_check(sels[i],ts_selectclass))
		{
			var hiddenfield=document.createElement('input');
			hiddenfield.name=sels[i].name;
			hiddenfield.type='hidden';
			hiddenfield.id=sels[i].id;
			hiddenfield.value=sels[i].options[0].value;
			sels[i].parentNode.insertBefore(hiddenfield,sels[i])
			var trigger=document.createElement('a');
			ts_addclass(trigger,ts_triggeroff);
			trigger.href='#';
			trigger.onclick=function(){
				ts_swapclass(this,ts_triggeroff,ts_triggeron)
				ts_swapclass(this.parentNode.getElementsByTagName('ul')[0],ts_dropdownclosed,ts_dropdownopen);
				return false;
			}
			trigger.appendChild(document.createTextNode(sels[i].options[0].text));
			sels[i].parentNode.insertBefore(trigger,sels[i]);
			var replaceUL=document.createElement('ul');
			for(var j=0;j<sels[i].getElementsByTagName('option').length;j++)
			{
				var newli=document.createElement('li');
				var newa=document.createElement('a');
				newli.v=sels[i].getElementsByTagName('option')[j].value;
				newli.elm=hiddenfield;
				newli.istrigger=trigger;
				newa.href='#';
				newa.appendChild(document.createTextNode(
				sels[i].getElementsByTagName('option')[j].text));
				newli.onclick=function(){ 
					this.elm.value=this.v;
					ts_swapclass(this.istrigger,ts_triggeron,ts_triggeroff);
					ts_swapclass(this.parentNode,ts_dropdownopen,ts_dropdownclosed)
					this.istrigger.firstChild.nodeValue=this.firstChild.firstChild.nodeValue;
					return false;
				}
				newli.appendChild(newa);
				replaceUL.appendChild(newli);
			}
			ts_addclass(replaceUL,ts_dropdownclosed);
			var div=document.createElement('div');
			div.appendChild(replaceUL);
			ts_addclass(div,ts_boxclass);
			sels[i].parentNode.insertBefore(div,sels[i])
			toreplace[count]=sels[i];
			count++;
		}
	}
	
/*
	Turn all ULs with the class defined above into dropdown navigations
	

	var uls=document.getElementsByTagName('ul');
	for(var i=0;i<uls.length;i++)
	{
		if(ts_check(uls[i],ts_listclass))
		{
			var newform=document.createElement('form');
			var newselect=document.createElement('select');
			for(j=0;j<uls[i].getElementsByTagName('a').length;j++)
			{
				var newopt=document.createElement('option');
				newopt.value=uls[i].getElementsByTagName('a')[j].href;	
				newopt.appendChild(document.createTextNode(uls[i].getElementsByTagName('a')[j].innerHTML));	
				newselect.appendChild(newopt);
			}
			newselect.onchange=function()
			{
				window.location=this.options[this.selectedIndex].value;
			}
			newform.appendChild(newselect);
			uls[i].parentNode.insertBefore(newform,uls[i]);
			toreplace[count]=uls[i];
			count++;
		}
	}
	for(i=0;i<count;i++){
		toreplace[i].parentNode.removeChild(toreplace[i]);
	}
	function ts_check(o,c)
	{
	 	return new RegExp('\\b'+c+'\\b').test(o.className);
	}
	function ts_swapclass(o,c1,c2)
	{
		var cn=o.className
		o.className=!ts_check(o,c1)?cn.replace(c2,c1):cn.replace(c1,c2);
	}
	function ts_addclass(o,c)
	{
		if(!ts_check(o,c)){o.className+=o.className==''?c:' '+c;}
	}
	
	*/
}
