﻿var queryString  = new PageQuery(window.location.search); 
var cat = parseInt(queryString.getValue('c'),10); if(isNaN(cat)) {cat=null}
var prod = parseInt(queryString.getValue('p'),10);  if(isNaN(prod)) {prod=null}
var brand = unescape(queryString.getValue('b'));
var range = unescape(queryString.getValue('r'));
var pageName = window.location.pathname.substring(window.location.pathname.indexOf('/'));

function goURL(pg){
    /// <summary>Automatically appends product related querystring parameters (c, p, b, r)</summary>
    /// <param name="pg">The destination page URL</param>
    var qs='';
    if(cat!='false') qs = 'c=' + escape(cat) + '&'
    if(prod!='false') qs += 'p=' + escape(prod) + '&'
    if(brand!='false') qs += 'b=' + escape(brand) + '&'
    if(range!='false') qs += 'r=' + escape(range) + '&'

    if (qs.length>0)
        if (typeof(pg)!='undefined')
            window.location = pg + '?' + qs.substring(0,qs.length-1);
        else
            window.location = pageName + '?' + qs.substring(0,qs.length-1);
    else
        if (typeof(pg)!='undefined')
            window.location = pg;
        else
            window.location = pageName;

}

function doSearch(searchTerm, searchFor){
    
    if(searchTerm && searchTerm.trim().length>0) {
        var url = String.format("/search.aspx?s={0}", escape(searchTerm));
        var urchinUrl = "/metrics/user/search/" + searchTerm;
        
        if (searchFor && searchFor.trim().length > 0) {
            url = String.format("{0}&f={1}", url, searchFor)
            urchinUrl = String.format("{0}/{1}",urchinUrl,searchFor);
        }
        urchinTracker(urchinUrl);

        window.location = url;
    }
    return false; //prevent postback
}

function printPage() {
    if (window.print) {
        window.print();
    } else {
        alert("Your browser doesn't support this feature.\nPlease try CTRL+P or CMD+P (Mac)");
    }
}

function subscribe(email){

    if (email && email.indexOf("@") > 0 && email.indexOf(".") > email.indexOf("@") + 1) {
        urchinTracker("/metrics/user/subscription/" + email);
        window.location = String.format("/membership/?email={0}", escape(email)); ;
    } else {
        alert("Invalid email!");
        setFocus(SubscribeText.get_id()+'_text', true);
    }
    return false; //prevent postback
}

function locateDealer(location){
    if (location && location.trim().length>0) {
        var qs = escape(location);
        if ($get("ProdInfo") != null) {
            product = $get("ProdInfo").innerHTML;
            qs += "&s=" + escape(product.substring(4, product.indexOf(":")));
        }
        window.location = String.format("/support/dealer_locator/?l={0}", qs);
    } else {
        alert("Invalid location!");
        setFocus(DealerLocatorText.id, true);
    }
    return false; //prevent postback
}

function setFocus(elementId, doSelect){
    /// <summary>Sets focus and optionally selects the contents of the given element. No error is triggered if the element does not support JavaScript focus() or select() methods</summary>
    /// <param name="elementId">The ID of the HTML element to receive focus</param>
    /// <param name="doSelect">A boolean indicating whether the contents of the HTML element should also be selected after receiving focus</param>
    var el = document.getElementById(elementId);
    if(el != null) {
        if(el.focus) el.focus();
        if(el.select && doSelect) el.select();
    }
}

//Generic AJAX call error handler (for unhandled errors)
function OnError_ServerReturn (arg, userContext) {
    hideAjax(userContext);
    alert('Error: ' + arg.get_message() + ' ' + arg.get_stackTrace()
          + '\n\nYour last action was probably not completed on the server.')
}

//Generic AJAX call complete handler. Server function must return a string containing "OK" or 
//the message to be displayed on completion (or handled error)
function OnSuccess_ServerReturn (result, userContext) {
    hideAjax(userContext);
    if (result != "OK") alert(result);
}

//Generic function to turn off the AJAX animation
function hideAjax(args){

    if (args!=null) {
        var node;

        if(typeof(args.get_node)=='function')
            node = args.get_node();
        else if(typeof(args.get_sourceNode)=='function')
            node = args.get_sourceNode();

        if (node!=null) 
            cmsBusy.Hide(node.get_treeView().get_id());
    }
}


//function disableControls(){
//    for (var i=0; i<document.forms[0].elements.length; i++){            
//        var obj = document.forms[0].elements[i];
//        obj.disabled = true;
//    }
//}

//function enableControls() {
//    for (var i=0; i<document.forms[0].elements.length; i++){        
//        var obj = document.forms[0].elements[i];
//        obj.disabled = false;
//    }
//}


var windowArgs = "resizable=no,toolbar=no,location=no,directories=no,status=no,scrollbars=no,menubar=no";

function popMFE(prodID, page, ref) {
	var mfeWin = window.open("/products/demo.aspx?prodID="+prodID+"&page="+page+"&ref="+ref, "mfe", "width=620,height=350,"+windowArgs);
	mfeWin.focus();
}

function popPlayer(path) {
	var playerWin = window.open("/flash/player/?path="+path, "player", "width=324,height=240,"+windowArgs);
	playerWin.focus();
}

function popWindow(url, id, width, height) {
	var newWin = window.open(url, id, "width="+width+",height="+height+","+windowArgs);
	newWin.focus();
}

function injectFlashMedia(file){

    if(file==null || file.length<7){return false}

    var assetHolderId = file.substring(file.lastIndexOf("/")+1,file.lastIndexOf(".")) + "_holder";
    if ($get(assetHolderId) == undefined) {
        alert(String.format("Asset holder '{0}' is missing", assetHolderId));
        return false;
    } else if ($get(assetHolderId).innerHTML.length > 0) {
        $get(assetHolderId).innerHTML="";
        $get(assetHolderId).style.display="none";        
        return false;
    }

    var fileExt = file.toLowerCase().substring(file.lastIndexOf(".")+1);
    var so;
    if(fileExt=="mp3"){
        so = new SWFObject("/flash/player/audio_player.swf", "aplayer", "324", "24", "7", "#FFFFFF");
    }else if(fileExt=="flv" || fileExt=="mp4"){
        so = new SWFObject("/flash/player/video_player.swf", "vplayer", "324", "240", "7", "#000000");
    }else if(fileExt=="swf") {
        so = new SWFObject(file, "SWFdemo", "324", "240", "7", "#000000");
    }

    so.addParam("allowScriptAccess", "always");
    so.addVariable("path", file);
    so.addVariable("auto", "true");
    so.write(assetHolderId);

    $get(assetHolderId).style.display="";        

}

function disableHighlighting(el){
    if (typeof el.onselectstart!="undefined") //IE
	    el.onselectstart=function(){return false}
    else if (typeof el.style.MozUserSelect!="undefined") //Firefox
	    el.style.MozUserSelect = "none"
}
function enableHighlighting(el){
    if (typeof el.onselectstart=="function") //IE
	    el.onselectstart=null
    else if (typeof el.style.MozUserSelect=="string") //Firefox
	    el.style.MozUserSelect=""
}


/*   Nuri validation functions  START */
function isDigit(src){return (src>='0') && (src<='9')}
function imposeMaxLength(el, MaxLen){return (el.value.length <= MaxLen)}
function getRadioSelection(el){
    myOption = -1;
    for (i=0; i<el.length; i++) {if (el[i].checked) {myOption = i}}
    if (myOption == -1) {return '`';}else{return el[myOption].value}
}
function isEmail(oSrc, args) {
    var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
    args.IsValid =  regex.test(args.Value);
}
function isValidCC(oSrc, args) {
    var nCheck = 0;
    var nDigit = 0;
    var bEven  = false;

    if(args.Value.length<15){args.IsValid = false;return;}

    for (n = args.Value.length - 1; n >= 0; n--) {
        var cDigit = args.Value.charAt (n);
        if (isDigit (cDigit)) {
            nDigit = parseInt(cDigit, 10);
            if (bEven) {
                if ((nDigit *= 2) > 9) nDigit -= 9;
            }
            nCheck += nDigit;
            bEven = ! bEven;
        }
        else if (cDigit != ' ' && cDigit != '.' && cDigit != '-'){
            args.IsValid = false;
            return;
        }
    }
    args.IsValid = (nCheck % 10) == 0;
}
function isValidCCExpiry(oSrc, args) {
    var regex = /^((0[1-9])|(1[0-2]))\/(\d{2})$/;
    args.IsValid =  regex.test(args.Value);
}

/*   Nuri validation functions  END */

function urchinTracker(url){
    try {
        pageTracker._trackPageview(url);
    } catch (err) { }
}

function tabClick(sender) {
    if (sender) {
       // If you don't set the onClick event to this tabClick() function the ajaxcontroltoolkit tab control 
       // FIRST hides the oldtab THEN shows the new tab. In Safari and Chrome, this makes the page jump 
       // and the tabs appear at the bottom of the page. 
       // Using sender.get_parent().set_activeTab(sender) doesn't help either.

        var oldTab = sender.get_parent().get_activeTab();
        if(sender != oldTab){
            sender.set_visible(true);
            oldTab.set_visible(false);
        
        }


        try {
            //when user clicks on any tab, if jQuery is active and there is a visible full article in this tab then hide full article and show list
            var divFullArticle = $("#" + sender.get_id() + " div.content div.singlearticle:visible")
            if (divFullArticle.length > 0) {
            
                var userControlId = divFullArticle[0].id.substring(0,divFullArticle[0].id.lastIndexOf("_"));
                
                //hide links
                var links = $("#" + userControlId + "_articleLinks");
                if(links.length>0) {
                    links[0].style.display = "none";
                }

                //hide full article and show article list
                var list = $("#" + userControlId + "_dlProductList");
                if (list.length > 0) {
                    divFullArticle[0].style.display="none";
                    list[0].style.display = "";
                }
            }
        } catch(err) {
        }


    }
}

var TopTabStrip; /* this object is set on first mouseover in function TopTabOnMouseOver() below */
var currentTab=null, tabTimeOutID = null;

function TopTabOnMouseOver(sender, args){
    TopTabStrip=sender;
    currentTab = args.get_tab();
    currentTab.select();

    //If the user moves out of the tab and comes back in before 
    //the timer expires, we need to clear the timer to stop the unselect() call
    if(tabTimeOutID!=null){
        clearTimeout(tabTimeOutID);
        tabTimeOutID=null;
    }
}
function TopTabOnMouseOut(sender, args){

    //tabTimeOut is a website parameter and set in Master.master.vb. If zero, then the menu never disappears.
    if(typeof(TopTabStrip)=='undefined' || currentTab==null || tabTimeOut<1 ){return false}

    //Find the element which the mouse is over   
    var destElement = args.get_domEvent().eventMapRelatedTarget;   

    //If that element is another tab in the tabstrip then exit (i.e. don't start the timer to unselect the tabstrip)
    if ($telerik.isDescendant(TopTabStrip.get_element(), destElement) && destElement.tagName == "LI") { return }

    //Otherwise set the tabstrip to 'unselect' the current tab after the time specified in tabTimeOut
    tabTimeOutID = setTimeout("TopTabStrip.set_selectedIndex(-1)", tabTimeOut);

} 

//function URLEncode (clearString) {
//  var output = '';
//  var x = 0;
//  clearString = clearString.toString();
//  var regex = /(^[a-zA-Z0-9_.]*)/;
//  while (x < clearString.length) {
//    var match = regex.exec(clearString.substr(x));
//    if (match != null && match.length > 1 && match[1] != '') {
//    	output += match[1];
//      x += match[1].length;
//    } else {
//      if (clearString.charCodeAt(x)==32)
//        output += '+';
//      else {
//        var charCode = clearString.charCodeAt(x);
//        var hexVal = charCode.toString(16);
//        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
//      }
//      x++;
//    }
//  }
//  return output;
//}

//Warning -  The following function is only to be used for testing to simulate a slow browser!
function pauseBrowser(ms) {
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); } 
    while(curDate-date < ms);
} 

// COOKIES //
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

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 eraseCookie(name) {
	createCookie(name,"",-1);
}


//QUERYSTRINGS
function PageQuery(q) {
    if(q.length > 1) this.q = q.substring(1, q.length);
    else this.q = null;
    this.keyValuePairs = new Array();
    if(q) {
        for(var i=0; i < this.q.split("&").length; i++) {
        this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }
    this.getKeyValuePairs = function() { return this.keyValuePairs; }
    this.getValue = function(s) {
        for(var j=0; j < this.keyValuePairs.length; j++) {
            if(this.keyValuePairs[j].split("=")[0] == s)
                return this.keyValuePairs[j].split("=")[1];
        }
        return false;
    }
    this.getParameters = function() {
        var a = new Array(this.getLength());
        for(var j=0; j < this.keyValuePairs.length; j++) {
            a[j] = this.keyValuePairs[j].split("=")[0];
        }
        return a;
    }
    this.getLength = function() { return this.keyValuePairs.length; } 
}

