﻿/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var keywords = "";



 function drawCircle(map, lat, lng, color, width, radius) {
            /*  Dev:    Google Groups
                Date:   2007-08-16
                Desc:   Draws a circles on the map at a set distance from the passed long lat.
                        Found on: http://www.reimers.dk/blogs/jacob_reimers_weblog/archive/2006/11/22/going-around-in-circles.aspx */
            
            var size = 3958.76 //Use 6371 for km
            var Clng = (radius/size)*(180/Math.PI)/Math.cos(lat*(Math.PI/180));
            var Cpoints = [];
            
            lng = parseFloat(lng);
            lat = parseFloat(lat);
            
            var swLat = 99999;
            var swLng = 99999;
            var neLat = -99999;
            var neLng = -99999;
            for (var i=0; i < 33; i++) {
                var theta = Math.PI * (i/16);
                Cx = lng + (Clng * Math.cos(theta));
                Cy = lat + ((radius/size)*(180/Math.PI) * Math.sin(theta));

                if(Cx < swLng){ swLng = Cx;}
                if(Cy < swLat){ swLat = Cy;}
                if(Cx > neLng){ neLng = Cx;}
                if(Cy > neLat){ neLat = Cy;}

                Cpoints.push(new GPoint(Cx,Cy));                
            };
  
  
            try{
                map.addOverlay(new GPolyline(Cpoints,color,width));
            } catch(e){}

            var swLoc = new GLatLng(swLat,swLng);
            var neLoc = new GLatLng(neLat,neLng);
            var gBounds = new GLatLngBounds(swLoc,neLoc);

            return gBounds;
        }
function doToggleSection(sSectionName, pairedSection)
{
    // Dev:     James Pearson
    // Date:    2007-06-22
    // Desc:    Toggles a section in the sidebar.
    // Updated: 2007-09-18      By: Steve Brockton
    // Note:    added paired section, when one opens, the other closes and vice versa
    if ($(sSectionName)) {
        var oIcon = $(sSectionName + '-icon');
        
        var aPathComps = oIcon.src.split("/");
        var filename = aPathComps[aPathComps.length-1]; 

        /*
        if(filename == 'bullet_arrow_up.png'){
            oIcon.src = 'http://' + aPathComps[2] + '/images/icons/bullet_arrow_down.png';
        } else {
            oIcon.src = 'http://' + aPathComps[2] + '/images/icons/bullet_arrow_up.png';
        }
        */
        var oContent = $(sSectionName + '-content');
        
        if(oContent.style.display == 'none'){
            new Effect.BlindDown(oContent.id,{scaleFrom:5});
            oIcon.src = 'http://' + aPathComps[2] + '/images/icons/bullet_arrow_up.png';
        } else {
            new Effect.BlindUp(oContent.id,{scaleTo:5});
            oIcon.src = 'http://' + aPathComps[2] + '/images/icons/bullet_arrow_down.png';
        }
        if ($(pairedSection)) {
            doToggleSection(pairedSection);
        }
    }
    
    return false;
    
}

function displayError(sMessage){
    // Dev:     James Pearson
    // Date:    2007-06-22
    // Desc:    Displays an error message on the screen
    
    
    
}
function isInteger(s){
    // Dev:     James Pearson
    // Date:    2007-06-10
    // Desc:    Checked is a string is an integer.
    
	var i = 0;
	
	for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function isNumeric(s) {
    // Dev:     Steve Brockton
    // Date:    2007-08-31
    // Desc:    Check whether string is numeric.
    var validChars = "0123456789.-";
    var oneChar;
    var blnResult = true;

    if (s.length == 0) return false;

    //  test s consists of valid characters listed above
    for (i = 0; i < s.length && blnResult == true; i++){
        oneChar = s.charAt(i);
        if (validChars.indexOf(oneChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}



function stripCharsInBag(s, bag){
    // Dev:     James Pearson
    // Date:    2007-06-10
    // Desc:    Strips a selection of letters from a string
    
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
    var minYear=07;
    var maxYear=99;
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay =dtStr.substring(0,pos1)
	var strMonth =dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 2 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 2 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
 
 
  function logError(msg,url,ln) {
      /*
        Dev:    James Pearson
        Date:   2007-06-11
        Desc:   Logs client side javascript errors via an Ajax callback
      */
  
        var strValues = "errMsg=" + escape(msg);
        strValues += "&errLine=" + ln;
        strValues += "&queryString=" + escape(location.search);
        strValues += "&Url=" + escape(location.pathname);
        strValues += "&HTTPRef=" + escape(document.referrer);

        new Ajax.Request('/clienterror.aspx?' + strValues, {method: 'get'})
}




function company_wizard()
{
        var url = 'http://' + document.domain + '/m/company/wizard/default.aspx'
        
           
        window.open(url,'DisplayCompany','resizable=1,scrollbars=1,width=500,height=300,top=60,left=60');
        
        return false;

}

function note_create(iCompanyID, iCompanyBranchID, iCompanyContactID)
{
        var url = 'http://' + document.domain + '/m/notes/popup/create.aspx?1=1'
        
        if(iCompanyID > 0){
            url += '&c=' + iCompanyID;
        }
        
        if(iCompanyBranchID > 0){
            url += '&cb=' + iCompanyBranchID;
        }
        
        if(iCompanyContactID > 0){
            url += '&cc=' + iCompanyContactID;
        }
        
        window.open(url,'DisplayNoteCreate','resizable=1,scrollbars=1,width=500,height=200,top=60,left=60');
        
        return false;

}

function contact_create(iCompanyID, iCompanyBranchID, iCompanyContactID)
{
        var url = 'http://' + document.domain + '/m/contacts/popup/create.aspx?1=1'
        
        if(iCompanyID > 0){
            url += '&c=' + iCompanyID;
        }
        
        if(iCompanyBranchID > 0){
            url += '&cb=' + iCompanyBranchID;
        }
        
        if(iCompanyContactID > 0){
            url += '&cc=' + iCompanyContactID;
        }
        
        window.open(url,'DisplayContactCreate','resizable=1,scrollbars=1,width=350,height=320,top=60,left=60');
        
        
        return false;
}

function calendarevent_create(iCompanyID, iCompanyBranchID, iCompanyContactID)
{
        var url = 'http://' + document.domain + '/m/eventcalendar/popup/create.aspx?1=1'
        
        if(iCompanyID > 0){
            url += '&c=' + iCompanyID;
        }
        
        if(iCompanyBranchID > 0){
            url += '&cb=' + iCompanyBranchID;
        }
        
        if(iCompanyContactID > 0){
            url += '&cc=' + iCompanyContactID;
        }
        
        window.open(url,'DisplayEventCreate','resizable=1,scrollbars=1,width=550,height=290,top=60,left=60');
        
        return false;

}

function privacy()
{
    var url = 'http://' + document.domain + '/m/help/privacy.aspx';
   
    if (window.open(url,'Privacy','resizable=1,scrollbars=1,width=500,height=260') == false){
        alert('Zubed failed to open a popup window. Please check your browser settings and try again');
    } 
    
    return false;

}


function message(iMemberID, iRequirementID, sSubject, sBody){
    var url = 'http://' + document.domain + '/m/messaging/create_popup.aspx?m='+ iMemberID;
    
    if(sSubject){
        url += '&r=' + iRequirementID;
    }
    
    if(sSubject){
        url += '&s=' + sSubject;
    }
    
    if(sBody){
        url += '&b=' + sBody;
    }
   
    if (window.open(url,'Message','resizable=1,scrollbars=1,width=550,height=450') == false){
        alert('Zubed failed to open a popup window. Please check your browser settings and try again');
    } 
    
    return false;
}




function clearAllSelected(elementName)
{
    var element = $(elementName);
    
    for (var i=0; i < element.options.length; i++) {
    
        element.options[i].selected = false;
                
   }
   
   return false;
}
    


// FROM: http://support.internetconnection.net/CODE_LIBRARY/javascript_Parsing_Query_String.shtml
function getRequestObject() {
    
    // The Object ("Array") where our data will be stored.
    FORM_DATA = new Object();
    
    separator = ',';
    
    // The token used to separate data from multi-select inputs
    query = '' + this.location;
    qu = query
    
    // Get the current URL so we can parse out the data.
    // Adding a null-string '' forces an implicit type cast
    // from property to string, for NS2 compatibility.
    
    query = query.substring((query.indexOf('?')) + 1);
    
    // Keep everything after the question mark '?'.
  
    if (query.length < 1) { return false; }  // Perhaps we got some bad data?
  keypairs = new Object();
  numKP = 1;
    // Local vars used to store and keep track of name/value pairs
    // as we parse them back into a usable form.
  while (query.indexOf('&') > -1) {
    keypairs[numKP] = query.substring(0,query.indexOf('&'));
    query = query.substring((query.indexOf('&')) + 1);
    numKP++;
      // Split the query string at each '&', storing the left-hand side
      // of the split in a new keypairs[] holder, and chopping the query
      // so that it gets the value of the right-hand string.
  }
  keypairs[numKP] = query;
    // Store what's left in the query string as the final keypairs[] data.<
  for (i in keypairs) {
    keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
      // Left of '=' is name.
    keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
      // Right of '=' is value.
    while (keyValue.indexOf('+') > -1) {
      keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
        // Replace each '+' in data string with a space.
    }
    keyValue = unescape(keyValue);
      // Unescape non-alphanumerics
    if (FORM_DATA[keyName]) {
      FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue;
        // Object already exists, it is probably a multi-select input,
        // and we need to generate a separator-delimited string
        // by appending to what we already have stored.
    } else {
      FORM_DATA[keyName] = keyValue;
        // Normal case: name gets value.
    }
  }
  return FORM_DATA;
}


// Processes an ISO date in to a javascript date.
// Found on: http://delete.me.uk/2005/03/iso8601.html
Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}



 /*
       name - name of the cookie
       value - value of the cookie
       [expires] - expiration date of the cookie
         (defaults to end of current session)
       [path] - path for which the cookie is valid
         (defaults to path of calling document)
       [domain] - domain for which the cookie is valid
         (defaults to domain of calling document)
       [secure] - Boolean value indicating if the cookie transmission requires
         a secure transmission
       * an argument defaults when it is assigned null as a placeholder
       * a null placeholder is not required for trailing omitted arguments
    */
    function setCookie(name, value, expires, path, domain, secure) {
      var curCookie = name + "=" + escape(value) +
          ((expires) ? "; expires=" + expires.toGMTString() : "") +
          ((path) ? "; path=" + path : "") +
          ((domain) ? "; domain=" + domain : "") +
          ((secure) ? "; secure" : "");
      //spitOut("setCookie: " + curCookie);
      document.cookie = curCookie;
    }


    /*
      name - name of the desired cookie
      return string containing value of specified cookie or null
      if cookie does not exist
    */
    function getCookie(name) {
      var dc = document.cookie;
      var prefix = name + "=";
      var begin = dc.indexOf("; " + prefix);
      if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
      } else
        begin += 2;
      var end = document.cookie.indexOf(";", begin);
      if (end == -1)
        end = dc.length;
      return unescape(dc.substring(begin + prefix.length, end));
    }


    /*
       name - name of the cookie
       [path] - path of the cookie (must be same as path used to create cookie)
       [domain] - domain of the cookie (must be same as domain used to
         create cookie)
       path and domain default if assigned null or omitted if no explicit
         argument proceeds
    */
    function deleteCookie(name, path, domain) {
      if (getCookie(name)) {
        document.cookie = name + "=" +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
      }
    }
    
    
    
    function doCloseSideBar(sExceptIDs)
    {
        var sExcept = sExceptIDs.split(",");
        
        sSecondaryObjects = document.getElementsByClassName('section', $('secondary'));
        
        var iSidebarCount = sSecondaryObjects.length ;
        for(var i=0; i<iSidebarCount; i++){
        
            if(!(sExcept.contains(sSecondaryObjects[i].id))){
                $(sSecondaryObjects[i].id + '-content').style.display = 'none';
                var oIcon = $(sSecondaryObjects[i].id + '-icon');
                var aPathComps = oIcon.src.split("/");
                var filename = aPathComps[aPathComps.length-1]; 
                oIcon.src = 'http://' + aPathComps[2] + '/images/icons/bullet_arrow_down.png';
            }
        }
        return false;
    }
    
    
    function baseDomainString(){
  e = document.domain.split(/\./);
  if(e.length > 1) {
    return("domain=" + e[e.length-2] + "." +  e[e.length-1]) + ";"  ;
  }else{
    return("");
  }
}


String.prototype.toProperCase = function() 
{
    return this.charAt(0).toUpperCase() + this.substring(1,this.length).toLowerCase();
}


function getSearchLocation()
{
//    var sLocation = $F('search-location');
//    if (sLocation == sSearchLocationsEmptyText){ sLocation = '';}
//    
//    return sLocation;
return '';
}

function getSearchKeywords()
{
//    var sKeywords = $F('search-keywords');
//    if (sKeywords == sSearchKeywordsEmptyText){ sKeywords = '';}
//    
//    return sKeywords;
return '';
}

function doSearch()
{
    var sURL = "/?1=1";
    
    var sKeywords = getSearchKeywords();
    var sLocation = getSearchLocation();
    
    if(sKeywords != ''){
        sURL += '&k=' + encodeURIComponent(sKeywords);
    }
    
    if(sLocation != ''){
        sURL += '&l=' + encodeURIComponent(sLocation);
    }
    window.location = sURL;
}
  
function fnTrapKD(event, advanced){
        if (document.all){
            if (event.keyCode == 13){
                event.returnValue=false;
                event.cancel = true;
                if (advanced && advanced==true) advancedSearch();
                else doSearch();
                return false;
            }
        }
        else if (document.getElementById){
            if (event.which == 13){
                event.returnValue=false;
                event.cancel = true;
                if (advanced && advanced==true) advancedSearch();
                else doSearch();
                return false;
            }
        }
        else if(document.layers){
            if(event.which == 13){
                event.returnValue=false;
                event.cancel = true;
                if (advanced && advanced==true) advancedSearch();
                else doSearch();
                return false;
                
            }
        }
        
    }
    
Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
};

// From http://www.somacon.com/p355.php
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function AddOptionToSelectList(list, value, text)
    // Dev: Richard Hughes
    // Date: 04/10/2007
    // Desc: this adds an option to the passed list
{
    // create the option
    var option = document.createElement("option");
    option.setAttribute("value", value);
    option.appendChild(document.createTextNode(text));

    // add the option
    list.appendChild(option);
}
function clearText(field){

 if (field.defaultValue == field.value){
    field.value = '';
    field.style.color = '#000000';
 } else if (field.value == ''){
    field.value = field.defaultValue;
    field.style.color = '#CECECE'
 }

}
function tell_a_friend_popup()
{

    window.open("http://www.zubedsales.com/m/contactus/TellAFriend.aspx","TellAFriend",'resizable=1,scrollbars=1,width=500,height=450,top=60,left=60');



}

function presentation_popup()
{

    window.open("http://www.zubedsales.com/m/Presentation/","Pres",'resizable=1,scrollbars=1,width=740,height=596,top=60,left=60');



}

function page_resize(){
    
     /*  Dev:    James Pearson
        Date:   2007-08-13
        Desc:   Resizes the main content area when the window is resized. 
                Partially based on the sample on http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ */
                
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerWidth != 'undefined')
    {
        viewportwidth = window.innerWidth,
        viewportheight = window.innerHeight
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
     else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
    {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
    }
    
    // older versions of IE
    
    else
    {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    
    
    var divPrimary = $('primary');
    var iHeightMod = 140;
    
    if(divPrimary){
        divPrimary.style.height = (viewportheight - iHeightMod) + 'px';
    }
	 
	var mapdiv = $('map');
	var container = $('map-container');
	
	if ((typeof map != 'undefined') && (typeof container != 'undefined'))
	{
	    container.style.height = (viewportheight - iHeightMod) + 'px';
	    mapdiv.style.height = (viewportheight - iHeightMod) + 'px';
	    
	    
	    try{
		    map.checkResize();
		}catch(err){}
    }

}

window.onresize = page_resize;
    