

/* General.js this file contains general javascript functions*/

function pop(u,n,f){
	var d = "default";
	var sf = "directories,location,menubar,resizable,scrollbars,status,toolbar";
	if (!n){n = d}
	if (!f){f = sf}
	pw = window.open(u,n,f);
	pw.focus();
}  
function switchDivs(elOn,elOff)
{
	ObjOn=document.getElementById(elOn);
	ObjOff=document.getElementById(elOff);
	ObjOn.style.display='block';
	ObjOff.style.display='none';
}

function toggle(el)
{      
   Obj=document.getElementById(el);
   if(Obj.style.display==''||Obj.style.display=='none') {
        Obj.style.display='block';     
   }
   else {
        Obj.style.display='none';
   }
}

function toggleClass(el,cl1,cl2)
{      
   Obj=document.getElementById(el);
   var isW3C = (document.getElementById(el)) ? true : false
   if (isW3C == true)
   {
       if(Obj.className!=cl1) {
            Obj.className=cl1;   
       }
       else {
            Obj.className=cl2;
       }
   }
}

function setClassOn(el,cl)
{
   Obj=document.getElementById(el);
   if(Obj.className!=cl) {
        Obj.className=cl;   
   }
}


function setClassOff(el,cl)
{
   Obj=document.getElementById(el);
   if(Obj.className==cl) {
        Obj.className='';
   }    
}

function setClass(el,cl)
{
   Obj=document.getElementById(el);
   if(Obj.className!=cl) {
        Obj.className=cl;   
   }
   else {
        Obj.className='';
   }
}

function setRegionSelect(el1,el2,cl){
    if(regionIsSet == false) {
        regionIsSet = true;
    }
    else {
        regionIsSet = false;
    }
    toggle(el1);
    setClass(el2,cl);
}

function cancelRegionSelect(el1,el2,cl) {
    if(regionIsSet == true) {
        regionIsSet = false;
        toggle(el1);
        setClass(el2,cl);    
    }
}

function setText(el,text) {
   Obj=document.getElementById(el);
   Obj.innerHTML=text;  

}

function setValue(el,text) {
   Obj=document.getElementById(el);
   Obj.value=text;  

}


var rollstates =
{   
    _cssPath:'/harrodsstore/css/harrods/',

    preload:function()
    {
        var a = document.getElementsByTagName('a'); //Gather all page anchors
        var i = a.length-1; //Number of links
        var styles,styleList,bg
        var j
        
        //Loop through all anchors looking for buttons
        do
        {
            if(-1 !=  a[i].className.indexOf('Btn')) //Just look for btn styles;
            {
                styleList = a[i].className.split(' ');//Cope with more than one class on the element
                j = styleList.length-1;
                
                do //Loop through classes on the element
                {
                    if(-1 !=  styleList[j].indexOf('Btn')) //Just look for btn styles;
                    {
                        styles = this._getHoverStyleBySelector('.'+styleList[j]); //Look for hover version of style in stylesheet
                        if (null != styles && styles.backgroundImage) //if found and it has a bg img then load it
                        {
                            bg = styles.backgroundImage;
                            bg = bg.substring(4,bg.length-1);//cut off url()
                            this._loadImg(bg);
                        }
                    }
                }while(0 < j--)
            }
        }while(0 < i--)
    },
     
    _getHoverStyleBySelector:function( selector )
    {
        var sheetList = document.styleSheets;
        var ruleList;
        var i, j;
        
        var retObj = {};
        
        /* look through stylesheets in reverse order that
           they appear in the document */
        for (i=sheetList.length-1; i >= 0; i--)
        {
            try //this might not work in some older browsers
            {
                ruleList = sheetList[i].cssRules ? sheetList[i].cssRules : sheetList[i].rules; // Get the style rules IE/Moz differ on how to call this.
                for (j=0; j<ruleList.length; j++) //loop through rules looking for the hover version of the passed in selector.
                   if (-1 != ruleList[j].selectorText.indexOf(selector) && -1 != ruleList[j].selectorText.indexOf(':hover')) //String hardcoded for speed.
                        return ruleList[j].style;
            }
            catch(err)
            {
                return null;
            }
        }
        return null;
    },
    
    _loadImg:function(filename)
    {
        filename = this._cssPath+filename;
        
        var img = new Image();
        img.src = filename;
        
        //document.writeln('<img src="'+filename+'" alt="" style="postion:absolute;border:0 !important"/>'); 
        document.writeln('<div style="background-image:url(' + filename + ')"></div>');
    }
}


/*
Copyright (c) Copyright (c) 2007, Carl S. Yestrau All rights reserved.
Code licensed under the BSD License: http://www.featureblend.com/license.txt
Version: 1.0.2
*/
var FlashDetect = new function(){
	var self = this;
	self.installed = false;
	self.major = -1;
	self.minor = -1;
	self.revision = -1;
	self.revisionStr = "";
	self.activeXVersion = "";
	var activeXDetectRules = [
		{
			"name":"ShockwaveFlash.ShockwaveFlash.7",
			"version":function(obj){
				return getActiveXVersion(obj);
			}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash.6",
			"version":function(obj){
				var version = "6,0,21";
				try{
					obj.AllowScriptAccess = "always";
					version = getActiveXVersion(obj);
				}catch(err){}
				return version;
			}
		},
		{
			"name":"ShockwaveFlash.ShockwaveFlash",
			"version":function(obj){
				return getActiveXVersion(obj);
			}
		}
	];
	var getActiveXVersion = function(activeXObj){
		var version = -1;
		try{
			version = activeXObj.GetVariable("$version");
		}catch(err){}
		return version;
	};
	var getActiveXObject = function(name){
		var obj = -1;
		try{
			obj = new ActiveXObject(name);
		}catch(err){}
		return obj;
	};
	var parseActiveXVersion = function(str){
		var versionArray = str.split(",");//replace with regex
		return {
			"major":parseInt(versionArray[0].split(" ")[1], 10),
			"minor":parseInt(versionArray[1], 10),
			"revision":parseInt(versionArray[2], 10),
			"revisionStr":versionArray[2]
		};
	};
	var parseRevisionStrToInt = function(str){
		return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
	};
	self.majorAtLeast = function(version){
		return self.major >= version;
	};
	self.FlashDetect = function(){
		if(navigator.plugins && navigator.plugins.length>0){
			var type = 'application/x-shockwave-flash';
			var mimeTypes = navigator.mimeTypes;
			if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
				var desc = mimeTypes[type].enabledPlugin.description;
				var descParts = desc.split(' ');//replace with regex
				var majorMinor = descParts[2].split('.');
				self.major = parseInt(majorMinor[0], 10);
				self.minor = parseInt(majorMinor[1], 10); 
				self.revisionStr = descParts[3];
				self.revision = parseRevisionStrToInt(self.revisionStr);
				self.installed = true;
			}
		}else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
			var version = -1;
			for(var i=0; i<activeXDetectRules.length && version==-1; i++){
				var obj = getActiveXObject(activeXDetectRules[i].name);
				if(typeof obj == "object"){
					self.installed = true;
					version = activeXDetectRules[i].version(obj);
					if(version!=-1){
						var versionObj = parseActiveXVersion(version);
						self.major = versionObj.major;
						self.minor = versionObj.minor; 
						self.revision = versionObj.revision;
						self.revisionStr = versionObj.revisionStr;
						self.activeXVersion = version;
					}
				}
			}
		}
	}();
};
FlashDetect.release = "1.0.2";

/* 
Derived from a script by Alejandro Gervasio. 
Modified to work in FireFox by Stefan Mischook for Killersites.com

How it works: just apply the CSS class of 'column' to your pages' main columns.
*/

function matchColumns(){
   
     var divs,contDivs,maxHeight,divHeight,d; 
	
     // get all <div> elements in the document 

     divs=document.getElementsByTagName('div'); 

     contDivs=[]; 

     // initialize maximum height value 

     maxHeight=0; 

     // iterate over all <div> elements in the document 

     for(var i=0;i<divs.length;i++){ 

          // make collection with <div> elements with class attribute 'container' 
          if(/\bcolumn\b/.test(divs[i].className)){ 

                d=divs[i]; 

                contDivs[contDivs.length]=d; 

                // determine height for <div> element 
                if(d.offsetHeight){
                     divHeight=d.offsetHeight;
                } 

                else if(d.style.pixelHeight){
                     divHeight=d.style.pixelHeight;
                } 

                // calculate maximum height 
                maxHeight=Math.max(maxHeight,divHeight);
          }
     }

     // assign maximum height value to all of container <div> elements 
     for(var i=0;i<contDivs.length;i++){
          contDivs[i].style.height=maxHeight + "px";
     }
} 

//MatchCol 2
function matchColumnsByClass(htmlClass){ 
 
     var divs,contDivs,maxHeight,divHeight,d,re;
	 var re = new RegExp(htmlClass);
     // get all <div> elements in the document 

     divs=document.getElementsByTagName('div'); 

     contDivs=[]; 

     // initialize maximum height value 

     maxHeight=0; 

     // iterate over all <div> elements in the document 

     for(var i=0;i<divs.length;i++){ 

          // make collection with <div> elements with class attribute 'container' 

          //if(/\bcolumn\b/.test(divs[i].className)){ 
          if(re.test(divs[i].className)){

                d=divs[i]; 

                contDivs[contDivs.length]=d; 

                // determine height for <div> element 

                if(d.offsetHeight){
                     divHeight=d.offsetHeight;
                }

                else if(d.style.pixelHeight){ 
                     divHeight=d.style.pixelHeight;
                }

                // calculate maximum height 
                maxHeight=Math.max(maxHeight,divHeight); 
          }
     }

     // No action if maxHeight not found
     if (isNaN(maxHeight)) return;
         
     // assign maximum height value to all of container <div> elements 
     for(var i=0;i<contDivs.length;i++){ 
        contDivs[i].style.height=maxHeight + "px"; 
     }
 }

 /*#### general address form functions #####*/

 function LoadCountryCodes(countryCode) {
     // Load country codes if not already loaded.
     if ($("[ID$='txtCountryName'] option").size() == 2) {

         $.ajax({
             type: "POST",
             contentType: "application/json; charset=utf-8",
             url: "/harrodsstore/Services/Account/AddressService.svc/GetCountryCodes",
             data: {},
             dataType: "json",
             error: function(xhr, status, error) {
                 var err = eval("(" + xhr.responseText + ")");
                 $('#ErrorView').text(err.Message).show();
                 $('#btnChange').hide();
                 return false;
             },
             success: function(msg) {

                 if (msg.d.isValid && null != msg.d.entityData) {
                     // Clear the list.
                     $("[ID$='txtCountryName']").children().remove();
                     // Add default option.
                     $("[ID$='txtCountryName']").append($('<option></option>').val("").html("Please Select"));
                     // Load list.
                     $.each(msg.d.entityData.items, function(key, item) {
                         $("[ID$='txtCountryName']").append($('<option></option>').val(item.Value).html(item.Text));
                     });

                     // Choose specified country.
                     $("[ID$='txtCountryName']").val(countryCode);
                 }
                 else {
                     $('#ErrorView').html(msg.d.errorMessage).show();
                 }
                 return false;
             }
         });
     }
     else {
         // Choose specified country.
         $("[ID$='txtCountryName']").val(countryCode);
     }
 }

 function LoadStateCodes(countryCode) {

     $("[ID$='ddStateList']").children().remove();

     var DTO = { 'countryCode': countryCode };

     $.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         url: "/harrodsstore/Services/Account/AddressService.svc/GetStateCodes",
         data: JSON.stringify(DTO),
         dataType: "json",
         error: function(xhr, status, error) {
             var err = eval("(" + xhr.responseText + ")");
             $('#ErrorView').text(err.Message).show();
             return false;
         },
         success: function(msg) {

             if (msg.d.isValid && null != msg.d.entityData) {
                 if (msg.d.entityData.items.length > 0) {
                     // Add default option.
                     $("[ID$='ddStateList']").append($('<option></option>').val("").html("Please Select"));
                     // Load list.
                     $.each(msg.d.entityData.items, function(key, item) {
                         $("[ID$='ddStateList']").append($('<option></option>').val(item.Value).html(item.Text));
                     });
                     $("[ID$='ddStateList']").show();
                     $("[ID$='txtRegion']").hide();
                 }
                 else {
                     $("[ID$='ddStateList']").hide();
                     $("[ID$='txtRegion']").show();
                 }
             }
             else {
                 $('#ErrorView').html(msg.d.errorMessage).show();
             }
             return false;
         }
     });
 }

 
 function GetRegionalLabels(countryShortCode) {

     var DTO = { 'countryShortCode': countryShortCode };

     $.ajax({
         type: "POST",
         contentType: "application/json; charset=utf-8",
         url: "/harrodsstore/Services/Account/AddressService.svc/GetRegionalLabels",
         data: JSON.stringify(DTO),
         dataType: "json",
         error: function(xhr, status, error) {
             var err = eval("(" + xhr.responseText + ")");
             $('#ErrorAdd').html(err.Message).show();
             return false;
         },
         success: function(msg) {
             if (msg.d.isValid && null != msg.d.entityData) {
                 $("#CityLabel").text(msg.d.entityData.CityLabel);
                 $("#RegionLabel").text(msg.d.entityData.RegionLabel);
                 $("#PostcodeLabel").text(msg.d.entityData.PostcodeLabel);
             }
             else {
                 $('#ErrorAdd').html(msg.d.errorMessage).show();
             }
             return false;
         }
     });

 }
 