﻿function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}

function ShowPopup(popUpId, objEvent)
{
    //var overlay = document.getElementById("overlay");
    var objPopUp = document.getElementById(popUpId);
    SetAllDimensionData(objEvent, objPopUp);
    objPopUp.style.visibility = "visible";
    if(objEvent != null)
    {
    //objPopUp.style.top = cursorY + 10 + "px";
    //objPopUp.style.left = cursorX - layerWidth / 2 + "px";
    }
}

function ClosePopup(popUpId)
{
    //var overlay = document.getElementById("overlay");
    var objPopUp = document.getElementById(popUpId);
    
    objPopUp.style.visibility = "hidden";
    //overlay.style.display = "none";
}

function AddWithComma(objTextBox, strData)
{
    objTextBox.value += strData + ",";
}

function CheckWithComma(objTextBox, strData)
{
    var index = objTextBox.value.indexOf(strData + ",");
    return (index != -1);
}

function RemoveWithComma(objTextBox, strData)
{
    objTextBox.value = objTextBox.value.replace(strData + ",", "");
}


/*
Browser Sniffer Script-
*/

function browserSniffer(browserCode, browserVersion) 
{
	var agt1 = navigator.userAgent.toLowerCase();
	var agt2 = navigator.appVersion.toLowerCase();
	if(browserCode==1)
	{	//check for IE
		if(browserVersion == 0)
		{
			if(agt2.indexOf("msie")!=-1)
				return true;
		}
		else
		{
			if(agt2.indexOf("msie " + browserVersion)!=-1)
				return true;
		}
	}
	else if(browserCode==2)
	{	//check for mozilla
		if(agt1.indexOf("firefox")!=-1)
			return true;
	}
	else if(browserCode==3)
	{	//check for safari
		if(agt2.indexOf("safari")!=-1)
			return true;
	}
	return false;
}


var bodyHeight, bodyWidth, cursorX, cursorY, layerHeight, layerWidth;

function SetAllDimensionData(objEvent, objLayer)
{
	layerHeight = objLayer.clientHeight;
	layerWidth = objLayer.clientWidth;

	scrollTop = document.documentElement.scrollTop;
	if(scrollTop==0)
		scrollTop = document.body.scrollTop;
		
	scrollLeft = document.documentElement.scrollLeft;
	if(scrollLeft==0)
		scrollLeft = document.body.scrollLeft;
	
	bodyHeight, bodyWidth;
	if(self.innerHeight)
	{	//for safari n mozilla
		bodyHeight = self.innerHeight;
		bodyWidth = self.innerWidth;
	}
	else
	{	//for IE 6+
		bodyHeight = document.documentElement.clientHeight;
		if(bodyHeight==0)	//for IE 5.5 -
			bodyHeight = document.body.clientHeight;
			
		bodyWidth = document.documentElement.clientWidth;
		if(bodyWidth==0)
			bodyWidth = document.body.clientWidth;
	}
	if(objEvent != null)
	{
	    cursorX = objEvent.clientX;
	    cursorY = objEvent.clientY;
	    if(browserSniffer(3, 0))
	    {	//if safari
		    cursorX = cursorX - scrollLeft;
		    cursorY = cursorY - scrollTop;
	    }
	}
}

function AdjustObjectWidthCustom(obj, width, attribute, reduceCount)
{   
     var sizeReduced = false;
     if(obj != null)
     {
        while(obj.offsetWidth > width)
        {            
            obj.attributes[attribute].value = obj.attributes[attribute].value.substring(0, obj.attributes[attribute].value.length - reduceCount);
            sizeReduced = true;
        }
        if(sizeReduced)
            obj.attributes[attribute].value += "...";
     }
}

function AdjustObjectWidth(obj, width, reduceCount)
{   
     var sizeReduced = false;
     if(obj != null)
     {
        while(obj.offsetWidth > width)
        {            
            obj.innerHTML = obj.innerHTML.substring(0, obj.innerHTML.length - reduceCount);
            sizeReduced = true;
        }
        if(sizeReduced)
            obj.innerHTML += "...";
     }
}

function GetURL()
{
	var url = document.URL;
	var indexOfQues = url.indexOf("?");
	if(indexOfQues!=-1)
	{
		url = url.substring(0, indexOfQues);
	}
	return url;
}

function GetPageName()
{
	var url = GetURL();
	var pageName = "";
	if(url.substring(url.length - 1) == '/' || url.substring(url.length - 1) == '\\')
	{
	    url = url.substring(0, url.length - 1);
	}
	var lastIndexOfSlash = url.lastIndexOf("/");
	if(lastIndexOfSlash == -1)
	    lastIndexOfSlash = url.lastIndexOf("\\");
	if(lastIndexOfSlash != -1)
	{
	    pageName = url.substring(lastIndexOfSlash + 1);
	}
	return pageName.toLowerCase();
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
        expires = expires * 1000 * 60;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


function hideEmptyContainersInLiveMode()
{
    $("div[FwObjectId] > span").each( function() 
    {
        if(this.innerHTML == "&nbsp;")
            this.parentNode.style.display = "none";
    })
 }


function HideDeafultText(objTextBox)
{
    if(objTextBox.getAttribute("defaultSetValue") == null)
    {
        objTextBox.setAttribute("defaultSetValue", objTextBox.value);
    }
    if(objTextBox.value == objTextBox.getAttribute("defaultSetValue"))
        objTextBox.value = "";
}

function ShowDeafultText(objTextBox)
{
    if(objTextBox.value == "")
    {
        if(objTextBox.getAttribute("defaultSetValue") != null)
        {
            objTextBox.value = objTextBox.getAttribute("defaultSetValue");
        }
    }
}

function HasTextChanged(objTextBox)
{
    var returnValue = false;
    
    if(objTextBox.value != "" && objTextBox.getAttribute("defaultSetValue") != null)
    {
        if(objTextBox.value != objTextBox.getAttribute("defaultSetValue"))
            returnValue = true;
    }
    
    return returnValue;
}

function fnTrapKD(btnID, e)
{
    if (e.keyCode == 13)
    {
        var btn = document.getElementById(btnID);
        e.returnValue=false;
        e.cancel = true;
        
        if (btn)
            btn.click();
    }
}

function getQueryString(key)
{
	var pageURL = "";
	pageURL = location.search;
	if(pageURL == "")
		return "";
	var indexOfKey = pageURL.indexOf("?" + key + "=");
	if(indexOfKey == -1)
		indexOfKey = pageURL.indexOf("&" + key + "=");
	if(indexOfKey == -1)
		return "";
	pageURL = pageURL.substring(indexOfKey+1);
	var indexOfEqualSign = pageURL.indexOf("=");
	if(indexOfEqualSign==-1)
		return "";
	var indexOfAmperSign = pageURL.indexOf("&");
	var queryString = "";
	if(indexOfAmperSign==-1)
		queryString = pageURL.substring(indexOfEqualSign + 1);
	else
		queryString = pageURL.substring(indexOfEqualSign + 1, indexOfAmperSign);
	return queryString;
}

function AddCondtion(filterCriteria, dataField, condition, like, addingClause)
{
    var likeChar = "%";
    var compareClause = "like"
    if(!like)
    {
        likeChar = "";
        compareClause = "=";
    }
    if(condition != "")
    {
        if(filterCriteria == "")
            filterCriteria = dataField + " " + compareClause + " '" + likeChar + condition + likeChar + "'";
        else
            filterCriteria = "( " + filterCriteria + " ) " + addingClause + " " + dataField + " " + compareClause + " '" + likeChar + condition + likeChar + "'";
    }
    
    return filterCriteria;
}


// JScript File
function ValidateThisUsercontrol(serverPrefix, grpName)
{
//alert(serverPrefix);
    return ValidateGroup(grpName);
}

function ValidateGroup(grpName)
{
    //alert(grpName);
    var returnValue = true;
    if(Page_Validators!=null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            if(Page_Validators[i].validationGroup == grpName)
            {   //if the validator of the required group, validate it
                if(Page_Validators[i].attributes["customGroup"]==null||Page_Validators[i].attributes["customGroup"].value=="alwaysValidate")
                {
                    if(!ValidateValidator(Page_Validators[i]))
                        returnValue = false;
                }
            }
        }
    }
    return returnValue;
}

function ValidateCustomGroup(customGroupName)
{
    //alert(grpName);
    var returnValue = true;
    if(Page_Validators!=null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            if(Page_Validators[i].attributes["customGroup"]!= null && Page_Validators[i].attributes["customGroup"].value == customGroupName)
            {   //if the validator of the required group, validate it
                //alert(ValidateValidator(Page_Validators[i]) + Page_Validators[i].id);
                if(!ValidateValidator(Page_Validators[i]))
                    returnValue = false;
            }
        }
    }
    return returnValue;
}

function ValidateGroupAndCustomGroup(grpName, customGrpName)
{
    var returnValue = true;
    if(Page_Validators!=null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            if(Page_Validators[i].validationGroup == grpName)
            {   //if the validator of the required group, validate it
                if(Page_Validators[i].attributes["customGroup"]==null || Page_Validators[i].attributes["customGroup"].value=="alwaysValidate" || Page_Validators[i].attributes["customGroup"].value==customGrpName)
                {
                    if(!ValidateValidator(Page_Validators[i]))
                        returnValue = false;
                }
            }
        }
    }
    return returnValue;
}

function ClearGroup(grpName)
{
    if(Page_Validators!=null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            if(Page_Validators[i].validationGroup == grpName)
            {   
                if(Page_Validators[i].attributes["customGroup"]==null||Page_Validators[i].attributes["customGroup"].value=="alwaysValidate")
                {
                    RemoveHighlight(Page_Validators[i]);
                }
            }
        }
    }
}

function ClearCustomGroup(customGroupName)
{    
    if(Page_Validators!=null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            if(Page_Validators[i].attributes["customGroup"]!= null && Page_Validators[i].attributes["customGroup"].value == customGroupName)
            {   
                RemoveHighlight(Page_Validators[i]);
            }
        }
    }
}

function ClearGroupAndCustomGroup(grpName, customGrpName)
{
    if(Page_Validators!=null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            if(Page_Validators[i].validationGroup == grpName)
            {   //if the validator of the required group, validate it
                if(Page_Validators[i].attributes["customGroup"]==null || Page_Validators[i].attributes["customGroup"].value=="alwaysValidate" || Page_Validators[i].attributes["customGroup"].value==customGrpName)
                {
                    RemoveHighlight(Page_Validators[i]);
                }
            }
        }
    }
}

function ValidatorValidate(val) {    
    val.isvalid = true;
    if (val.enabled != false) {
        if (typeof(val.evaluationfunction) == "function") {
            val.isvalid = val.evaluationfunction(val); 
        }
    }
    ValidatorUpdateDisplay(val);
}

function ValidateValidator(validator)
{
    var returnValue;
    if(validator.attributes["controlToValidateType"] != null && validator.attributes["controlToValidateType"].value == "RadioButtonList" && validator.attributes["validatorType"]!= null && validator.attributes["validatorType"].value == "RequiredFieldValidator")
        ValidateIfRadioChecked(validator);
    else
        ValidatorValidate(validator);
    //alert(Page_Validators[i].isvalid + Page_Validators[i].id);
    if(!validator.isvalid)
    {   //if not validate
        returnValue = false;
        HighlightError(validator);
    }
    else
    {
        returnValue = true;
        RemoveHighlight(validator);
    }
    return returnValue;
}

function ValidateIfRadioChecked(validator)
{
    var radioControlsIdPrefix = validator.controltovalidate;
    var radioChecked = false;
    var i = 1;
    var radioObj = document.getElementById(radioControlsIdPrefix + i);
    
    for(i = 2; radioObj!=null; i++)
    {
        if(radioObj.checked)
        {
            radioChecked = true;
            break;
        }
        
        radioObj = document.getElementById(radioControlsIdPrefix + i);
    }
    validator.isvalid = radioChecked;
}

function HighlightError(validator)
{
    if(validator.attributes["headingControlId"]!=null)
    {
        var headingControlId = validator.attributes["headingControlId"].value;
        var headingControlObj = document.getElementById(headingControlId);
        //Change Header Text Color
        if(headingControlObj!=null)
        {
            AppendErrorClass(headingControlObj);
            headingControlObj.lastValidatorFailed = validator.id;
        }
    }
    //alert(headingControlObj);
    
    if(validator.attributes["messageControlId"]!=null)
    {
        var messageControlId = validator.attributes["messageControlId"].value;
        var messageControlObj = document.getElementById(messageControlId);
        
            
        //Display error message if exists
        if(messageControlObj!=null)
        {
            AppendErrorClass(messageControlObj);
            messageControlObj.lastValidatorFailed = validator.id;
        }
    }
}
function HighlightTextbox(obj)
{
    obj.style.border = "red solid 1px";
}
function UnHighlightTextbox(obj)
{
    obj.style.border = "#abadb3 solid 1px";
}

function AppendErrorClass(obj)
{
    obj.className += " errorMessage";
}

function RemoveErrorClass(obj)
{
    obj.className = obj.className.replace(/errorMessage/g, "");
}

function RemoveHighlight(validator)
{
    if(validator.attributes["headingControlId"] != null)
    {
        var headingControlId = validator.attributes["headingControlId"].value;
        var headingControlObj = document.getElementById(headingControlId);
        //Change Header Text Color
        if(headingControlObj!=null && headingControlObj.lastValidatorFailed == validator.id)
        {
            RemoveErrorClass(headingControlObj);
        }
    }
        
    if(validator.attributes["messageControlId"] != null)
    {
        var messageControlId = validator.attributes["messageControlId"].value;
        var messageControlObj = document.getElementById(messageControlId);
        
            
        //Display error message if exists
        if(messageControlObj!=null && messageControlObj.lastValidatorFailed == validator.id)
        {
            RemoveErrorClass(messageControlObj);
        }
    }
}

function GetChildObject(obj, tagName, attribute, value)
{
	var i;
	
	for(i=0; i<obj.childNodes.length; i++)
	{
		
		if(obj.childNodes[i].nodeName == tagName)
		{
			if(attribute!=null && attribute!="")
			{
			    if(obj.childNodes[i].attributes[attribute] != null)
				    if(obj.childNodes[i].attributes[attribute].value.indexOf(value)!=-1)
					    return obj.childNodes[i];
			}
			else
			{
				return obj.childNodes[i];
			}
		}
	}
	return null;
}

function GetAllRecursiveChildObjects(obj, tagName, attribute, value, childObjects)
{
	var i;
	
	for(i=0; i<obj.childNodes.length; i++)
	{
		//alert(i + " : " + obj.nodeName + " : " + obj.childNodes[i].nodeName);
		if(obj.childNodes[i].nodeName == tagName)
		{
			if(attribute!=null && attribute!="" && obj.childNodes[i].attributes[attribute] != null)
			{
				if(obj.childNodes[i].attributes[attribute].value.indexOf(value)!=-1)
				{
					childObjects[childObjects.length] = obj.childNodes[i];
					continue;
				}
			}
			else
			{
				childObjects[childObjects.length] = obj.childNodes[i];
				continue;
			}
		}
		
		GetAllRecursiveChildObjects(obj.childNodes[i], tagName, attribute, value, childObjects);
	}
	return childObjects;
}

function GetParentObject(obj, tagName, attribute, value)
{
	var i;
	
	while(obj.parentNode.nodeName!="BODY"&&obj.parentNode.nodeName!="HTML")
	{
		if(obj.parentNode.nodeName == tagName)
		{
			if(attribute!=null && attribute!="")
			{
			    if(obj.parentNode.attributes[attribute] != null)
				    if(obj.parentNode[attribute].value.indexOf(value)!=-1)
					    return obj.parentNode;
			}
			else
			{
				return obj.parentNode;
			}
		}
		
		obj = obj.parentNode;
	}
	
	return null;
}

function fnTrapKD(btnID, e)
{
    if (e.keyCode == 13)
    {
        var btn = document.getElementById(btnID);
        e.returnValue=false;
        e.cancel = true;
        
        if (btn)
            btn.click();
    }
}

function CheckCreditCardNumberFormat(cardnumber, cardname) 
{
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "36,54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards[4] = { name: "American Express", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++)
  {
    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) 
    {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) 
  {
     return "Unknown card type.";
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  
  {     
     return "No card number provided."; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  
  {
     return "Credit card number is in invalid format."; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) 
  {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) 
    {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) 
      {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  
    {     
     return "Credit card number is invalid."; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) 
  {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) 
  {     
     return "Credit card number is invalid."; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) 
  {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) 
  {
     return "Credit card number has an inappropriate number of digits."; 
  };   
  // The credit card is in the required format.
  return "true";
}


var shownPopUp = new Array();
var overlays = new Array();
var popUpsOpenedCount = 0;
var pageSize;
function ShowModalPopup(popUpId)
{
    var overlay;
    var objPopUp = document.getElementById(popUpId);
    
    if(popUpsOpenedCount == 0)
    {
        overlay = document.getElementById("overlay");
        pageSize = getPageSize(objPopUp);
        overlay.style.display = "block";
        overlay.style.width = pageSize[0] + "px";
        overlay.style.height = pageSize[1] + "px";
        overlay.style.zIndex = 50;
        
        objPopUp.style.visibility = "visible";
        objPopUp.style.top = pageSize[7] + pageSize[3]/2 - pageSize[5]/2 + "px";
        objPopUp.style.left = pageSize[6] + pageSize[2]/2 - pageSize[4]/2 + "px";
        objPopUp.style.zIndex = 100;
    }
    else
    {
        overlay = document.getElementById("overlay" + popUpsOpenedCount);
        overlay.style.display = "block";
        overlay.style.width = objPopUp.parentNode.clientWidth + "px";
        overlay.style.height = objPopUp.parentNode.clientHeight + "px";
        objPopUp.style.zIndex = (popUpsOpenedCount + 1) * 1000;
        
        objPopUp.style.visibility = "visible";
        var left = (objPopUp.parentNode.clientWidth - objPopUp.clientWidth) / 2;
        var top = (objPopUp.parentNode.clientHeight - objPopUp.clientHeight) / 2;
        var parentTop = parseInt(objPopUp.parentNode.style.top.replace("px", ""));
        var pageStartTop = 0;
        /*if(browserSniffer(1, 0))
        {
            pageStartTop = 0;
        }
        else if(browserSniffer(2, 0))
        {
            pageStartTop = 0;
        }*/
        if(top < pageStartTop)
            objPopUp.style.top = pageStartTop + "px";
        else
            objPopUp.style.top = top + "px";
        objPopUp.style.left = left + "px";
        overlay.style.zIndex = (popUpsOpenedCount + 1) * 1000 - 5;
    }
    
    overlays[popUpsOpenedCount] = overlay;
    shownPopUp[popUpsOpenedCount++] = objPopUp;
}

function CloseModalPopup()
{
    if(popUpsOpenedCount != 0)
    {
        popUpsOpenedCount--;
        var overlay = document.getElementById("overlay");
        shownPopUp[popUpsOpenedCount].style.visibility = "hidden";
        overlays[popUpsOpenedCount].style.display = "none";
    }
}
function getPageSize(objLayer)
{
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body != null && document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	var pageHeight, pageWidth;
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

    if(objLayer != null)
    {
        layerHeight = objLayer.clientHeight;
	    layerWidth = objLayer.clientWidth;
	}
	
	var scrollTop = document.documentElement.scrollTop;
	if(scrollTop==0)
		scrollTop = document.body.scrollTop;
		
	var scrollLeft = document.documentElement.scrollLeft;
	if(scrollLeft==0)
		scrollLeft = document.body.scrollLeft;

	arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight, layerWidth, layerHeight, scrollLeft, scrollTop) 
	return arrayPageSize;
}

var popUpLayerShown = null;

function ShowMouseOverPopUpLayer(layerId, objEvent)
{
    if(objHidePopUpInterval != null)
	{
	    clearTimeout(objHidePopUpInterval);
	}
	
	var objLayer = document.getElementById(layerId);
	
	cancelAllTimeOuts = true;
	
	if(!IsLayerShown(popUpLayerShown))
	{//else only if layer is not shown continue
		popUpLayerShown = objLayer;		
		
		var objArrow = GetChildObject(objLayer, "IMG", "class", "directionArrow");
		
		SetAllDimensionData(objEvent, objLayer);
		
		//alert("Layer Height: " + layerHeight + " Layer Width: " + layerWidth);
		//alert("Scroll Top: " + scrollTop + " Scroll Left: " + scrollLeft);
		//alert("Body Height: " + bodyHeight + " Body Width: " + bodyWidth);
		//alert("Cursor Y: " + cursorY + " Cursor X: " + cursorX);
		
		//alert(cursorY);
		//alert(objLayer.clientHeight);
		//show the layer
		objLayer.style.visibility = "visible";
		
		//set the top position of the pop up
		if(cursorY<layerHeight/2)
		{	//space on top is less, show starting from browser top
			objLayer.style.top = scrollTop + 5 + "px";
			objArrow.style.marginTop = cursorY + "px";
		}
		else if((bodyHeight-cursorY)<layerHeight/2)
		{	//space on bottom is less, show ending from browser bottom
			objLayer.style.top = scrollTop + bodyHeight - layerHeight - 5 + "px";
			if(cursorY - (bodyHeight - layerHeight)>layerHeight - 40)
				objArrow.style.marginTop = cursorY - (bodyHeight - layerHeight) - 36 + "px";
			else
				objArrow.style.marginTop = cursorY - (bodyHeight - layerHeight) + "px";
		}
		else
		{	//enough place on both top n bottom, place layer in center
			objLayer.style.top = scrollTop + cursorY - layerHeight/2 + "px";
			objArrow.style.marginTop = (layerHeight-31)/2 + "px";
		}
		//set the top position of the pop up
		if(cursorX>bodyWidth/2)
		{	//open box on left
			objLayer.style.left = cursorX + scrollLeft - layerWidth - 20 + "px";		
			objArrow.src = "/images/popUpDirectionRight.gif";
			objArrow.style.left = layerWidth + "px";
		}
		else
		{	//open box on right
			objLayer.style.left = cursorX + scrollLeft + 20 + "px";
			objArrow.src = "/images/popUpDirectionLeft.gif";
			objArrow.style.left = "-17px";
		}
		
		objLayer.focus();	
	}
}

var continuueShowing = false;
var objHidePopUpInterval = null;
var cancelAllTimeOuts = false;
function SetContinueShowing()
{
    continuueShowing = true;
}

function HideMouseOverPopUpLayer()
{
	if(popUpLayerShown!=null && !continuueShowing)
	{
		popUpLayerShown.style.visibility = "hidden";
		popUpLayerShown.style.top = "0px";
		popUpLayerShown.style.left = "0px";
		objHidePopUpInterval = null;
	}
}

function HideMouseOverPopUpLayerTO()
{
	if(!cancelAllTimeOuts)
	{
	    HideMouseOverPopUpLayer();
	}
}

function HideMouseOverPopUpLayerOnTimeOut()
{
    cancelAllTimeOuts = false;
    objHidePopUpInterval = setTimeout(HideMouseOverPopUpLayerTO, 500);
}

function ForceHideMouseOverPopUpLayer()
{
    continuueShowing = false;
    HideMouseOverPopUpLayerOnTimeOut();
}

function IsLayerShown(obj)
{
	if(obj!=null)
	{
		if(obj.style.visibility=="visible")
			return true;
	}
	return false;
}

function SetArticleLink(linkname, mainid, sideid1, sideid2)
{
    var Hyperlink = document.getElementById(linkname);
    if (Hyperlink != null)
    {
        Hyperlink.href += "?ID=" + mainid;
        if (sideid1 != '')
        {
            Hyperlink.href += "&AID1=" + sideid1;
        }
        if (sideid2 != '')
        {
            Hyperlink.href += "&AID2=" + sideid2;
        }
    }
}

function PreLoadImages(urlPrefix, image_url)
{
    if (document.images)
    {
      var preload_image_object = new Image();

      var i;
      for(i = 0; i < image_url.length; i++) 
         preload_image_object.src = urlPrefix + image_url[i];
    }
 }


function OnKeyUpShiftFocus(objText, numberOfDigits, evt)
{
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if(charCode == 9 || charCode == 16 || (charCode >= 37 && charCode <= 40))
        return
    var phonePrefix = objText.id.substring(0, objText.id.length-1);
    var phoneIndex = parseInt(objText.id.substring(objText.id.length-1)) + 1;
    if(objText.value.length == numberOfDigits)
    {
        document.getElementById(phonePrefix + phoneIndex).focus();
        document.getElementById(phonePrefix + phoneIndex).select();
    }
}

function UpdateTelephoneNumber(objTextBox)
{  
    var phonePrefix = objTextBox.id;
    var phoneNum = phonePrefix.substring(0,phonePrefix.length-1);
    var phoneNumber = "";
    for(var i=1; i<=3; i++)
    {
        phoneNumber += document.getElementById(phoneNum + i).value;
    }
    document.getElementById(phoneNum).value = phoneNumber;
    return;
}

function getQueryString(key)
{
	var pageURL = "";
	pageURL = location.search;
	if(pageURL == "")
		return "";
	var indexOfKey = pageURL.indexOf("?" + key + "=");
	if(indexOfKey == -1)
		indexOfKey = pageURL.indexOf("&" + key + "=");
	if(indexOfKey == -1)
		return "";
	pageURL = pageURL.substring(indexOfKey+1);
	var indexOfEqualSign = pageURL.indexOf("=");
	if(indexOfEqualSign==-1)
		return "";
	var indexOfAmperSign = pageURL.indexOf("&");
	var queryString = "";
	if(indexOfAmperSign==-1)
		queryString = pageURL.substring(indexOfEqualSign + 1);
	else
		queryString = pageURL.substring(indexOfEqualSign + 1, indexOfAmperSign);
	return queryString;
}

function PreLoadDealerNavImages(colorSchemeName, setNumber, extension)
    {
         var images = new Array();
         images[0]="/Images/Set" + setNumber + "/" + colorSchemeName + "/CarpetH." + extension;
         images[1]="/Images/Set" + setNumber + "/" + colorSchemeName + "/HardwoodH." + extension;
         images[2]="/Images/Set" + setNumber + "/" + colorSchemeName + "/AreaRugH." + extension;
         images[3]="/Images/Set" + setNumber + "/" + colorSchemeName + "/TileStoneH." + extension;
         images[4]="/Images/Set" + setNumber + "/" + colorSchemeName + "/LaminateH." + extension;
         images[5]="/Images/Set" + setNumber + "/" + colorSchemeName + "/MoreHomeH." + extension;
         images[6]="/Images/Set" + setNumber + "/" + colorSchemeName + "/ServicesH." + extension;
         images[7]="/Images/Set" + setNumber + "/" + colorSchemeName + "/PromotionsH." + extension;
         images[8]="/Images/Set" + setNumber + "/" + colorSchemeName + "/MoreHomeH." + extension;
         images[9]="/Images/Set" + setNumber + "/" + colorSchemeName + "/TileStoneH." + extension;
         // create object
         
         for(var i=0; i<images.length; i++) 
         {
            var imageObj = new Image();
              imageObj.src=images[i];
              //alert(images[i]);
         }
    }
    
    
    function SetPromotionsLink(objA, parentDiv)
    {
        var anchors = new Array();
        GetAllRecursiveChildObjects(parentDiv, "A", null, null, anchors);
        
        if(anchors.length == 2)
        {
            var innerAnchorTag = anchors[1];
            objA.href = innerAnchorTag.href;
            objA.target = innerAnchorTag.target;
        }
    }
    
    
    //call to google map api

    var map = null;
    var geocoder = null;
    var arrPoints = new Array();
    var arrAddLoaded = new Array(false, false, false, false, false, false, false, false, false, false, false, false,false, false, false, false, false, false, false, false, false, false, false, false);

    function initializeGMA() {
      if (GBrowserIsCompatible()) {
        
        //map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        geocoder = new GClientGeocoder();
      }
    }
    
    function ShowGoogleMap(dAddress, directionsLink, e, index)
    {
        var msgSorry = document.getElementById("msgSorry");
        var imgLoading = document.getElementById("imgLoading");
        var map_canvas = document.getElementById("map_canvas");
        imgLoading.style.display = "block";
        map_canvas.style.display = msgSorry.style.display = "none";
        showAddress(dAddress, directionsLink, index);
        HideMouseOverPopUpLayer();
        ShowMouseOverPopUpLayer("mouseOverImage", e);
    }

    function showAddress(address, url, index)
    {
        lastAddress = address;
        lastURL = url;
        lastIndex = index;
        if(!arrAddLoaded[index])
        {
            if (geocoder) 
            {
                //alert(address);
                geocoder.getLatLng( address, SetPointOnMap);
            }
        }
        else
        {
            SetPointOnMap(arrPoints[index]);
        }
    }
    
    var lastAddress;
    var lastURL;
    var lastIndex;
    function SetPointOnMap(point)
    {
        //alert(point);
            var bubbleMessage = "<font color='black'>" + lastAddress + "</font><Br />" + "<a href='" + lastURL + "' target='_blank' style='color: #000;'>Get Directions</a>";
            if(!arrAddLoaded[lastIndex])
            {
                arrPoints[lastIndex] = point;
                arrAddLoaded[lastIndex] = true;
            }
            var msgSorry = document.getElementById("msgSorry");
            var imgLoading = document.getElementById("imgLoading");
            var map_canvas = document.getElementById("map_canvas");
            imgLoading.style.display = "none";
            if (!point)
            {
              msgSorry.style.display = "block";
            } 
            else 
            {
                map_canvas.style.display = "block";
                map = new GMap2(map_canvas);
                map.setCenter(point, 13);
                var marker = new GMarker(point);
                map.addOverlay(marker);
                //alert(bubbleMessage);
                marker.openInfoWindowHtml(bubbleMessage);
            }
    }
    
    
    var frmLoaded = new Array(false, false, false, false, false, false, false, false, false, false, false, false,false, false, false, false, false, false, false, false, false, false, false, false);
    function ShowMapInIframe(sAddress, directionURL, displayType, e, index, sURL)
    {
        HideMouseOverPopUpLayer();
        ShowMouseOverPopUpLayer("mouseOverImage", e);
        $("div.dvMaps").css('display', 'none');
        $("div#dvMaps" + index).css('display', 'block');
        if(!frmLoaded[index])
        {
            var imgLoading = document.getElementById("imgLoading");
            imgLoading.style.display = "block";
            window.frames["maps" + index].window.location = sURL + '/smhome/maps?A=' + sAddress + "&D=" + directionURL + "&T=" + displayType;
            frmLoaded[index] = true;
        }
    }
    function IFrameLoaded()
    {
        var imgLoading = document.getElementById("imgLoading");
        imgLoading.style.display = "none";
    }


