﻿var queryString  = new PageQuery(window.location.search); 
var cat = unescape(queryString.getValue('c'));
var prod = unescape(queryString.getValue('p'));
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){
    
    if(searchTerm && searchTerm.trim().length>0) {
        var url = String.format("/hybridsearch.aspx?s={0}", URLEncode(searchTerm));
        window.location = url;
    }
    return false; //prevent postback
}

function subscribe(email){
    if (email && email.indexOf("@") > 0 && email.indexOf(".", email.indexOf("@")) > 0) {
        window.location = String.format("/membership/?email={0}", URLEncode(email)); ;
    } else {
        alert("Invalid email!")
    }
    return false; //prevent postback
}

function locateDealer(location, permit) {
    if (location && location.trim().length > 0) {
        window.open('http://www.roland.co.uk/Qas/nearweb.asp?Permit==' + permit + '&Query=' + location, 'DealerLocator', 'location=yes,scrollbar=yes,width=700,height=500');
    } else {
        alert('Enter your postcode.');
    }
    return false;
/*    if (location && location.trim().length>0) {
        window.location = String.format("/support/dealer_locator/?loc={0}", URLEncode(location)); ;
    } else {
        alert("Invalid location!")
    }
    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 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 isEmail(src) {var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;return regex.test(src);}
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 isValidCC(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;
}
/*   Nuri validation functions  END */

//Dummy function to avoid error thrown by MFE if no Google Analytics is used
function urchinTracker(url) {
    try {
        pageTracker._trackPageview(url);
    } 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[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

// 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; } 
}

// Called From radGrid in BannerManager.aspx and MediaManager.aspx
function conditionalPostback(e, sender) {
    if (sender.EventTarget.indexOf("$btnUpdate")>-1){
        //find the upload INPUT tag by class
        var arInputs = document.getElementsByTagName("input");
        var sFileToUpload = '';
        for (i=0; i<arInputs.length; i++){
            if (arInputs(i).className=='RadUploadInputField')
                sFileToUpload = arInputs(i).value;
        }
        if(sFileToUpload!='') //If there is a file to upload then disable radAjax
            sender.EnableAjax = false;
    }
}

