﻿// v1.0 051607 ap   - created
// v1.1 051607 ap   - debugged, cleaned up
// v1.2 051707 ap   - making sure the countryOffices object is being created
// v1.3 051707 ap   - modified loop to include else if for international selections
// v1.4 051807 ap   - add another address line: mailingAddress
// v1.5 052207 ap   - editing to suit loadOffices & loadContactInfo JS
// v1.6 052407 ap   - adding functions for date, time for use with order form
// v1.7 052507 ap   - cleaned up
// v1.8 052807 ap   - added isInternational() function

// javascript library for Linwood Homes Ltd.

// common code to be shared between loadOffices.js and loadContactInfo.js

// onload function to init lightbox
// window.onload=function(){initLightbox()};
// window.attachEvent("onload",initLightbox();)

// retrieves query string
// returns array of strings, formatted with " " instead of %20
function getQS(){
    var qs="";
    // extract the query string from the address bar
	if ( parent.location.search == "" ){
		qs = location.search.substring( 1, location.search.length );	
	} 
	else{
		qs = parent.location.search.substring( 1, parent.location.search.length ); 
	}
	// grabs the query string, extracts the required string and re-saves into var
	qs = qs.split( '&' );
//	alert('qs length is: '+qs.length)
	if (1<qs.length){
//	    alert('evaluating qs')
	    evaluateQS(qs);
	}//else{alert('no need to evaluate qs...returning value '+qs)}
	return qs;
}
// HELPER FUNCTIONS | added 042007AP
// will check for "%20" in the query string and re-format it for geocoding purposes
function evaluateQS(str){
    for (x=0;x<str.length;x++){
        if (str[x]){
            var s=str[x];
            str[x]=check(s);
        }
    }
    return str;
}
// todo: to check for %28 & %29 "(",")" in the future
function check(string){
    if (string.search("%20")!=-1){
        string=string.split('%20');
        var str="";
        for (i=0;i<string.length;i++){
            if (i!=string.length-1){
                str += string[i]+" ";
            }else{str+= string[i];}
        }
    }else{str=string;}
    return str;
}

// retrieves offices by country
function objOffices(xml,country){
    var numCountries,numOffices,countryOffices;
    numCountries = xml.getElementsByTagName('location').length;

    function getObject(){
        for (k=0;k<=numCountries-1;k++){
//            alert('xml location: '+xml.getElementsByTagName('location')[k].getAttribute('name')+'\n'+
//                'country from querystring: '+country.toLowerCase()
//            )
            if ( country.toLowerCase()==xml.getElementsByTagName('location')[k].getAttribute('name') ){
//            if ( country==xml.getElementsByTagName('location')[k].getAttribute('name') ){
//                alert('found match: '+country.toLowerCase()+' | '+xml.getElementsByTagName('location')[k].getAttribute('name'))
                countryOffices = xml.getElementsByTagName('location')[k];
                break;
            }
            else if(xml.getElementsByTagName('location')[k].getAttribute('name')=='int'){
//                alert('found match: '+country.toLowerCase()+' | '+xml.getElementsByTagName('location')[k].getAttribute('name'))
                countryOffices = xml.getElementsByTagName('location')[k];
            }
            // if it's another country (in the case of international dealers) the objects are simply returned
//            else{alert('not canada, us or int.  processing for international dealers...')}
        }return countryOffices;
    }


    this.getOffices = function(){
        // only grab offices from said location(country) by
        // adding the prefix countryOffices to .getElementsByTagName('office')...
        
        getObject();
        
//        alert('getting offices...'+String(countryOffices))
        
        numOffices = countryOffices.getElementsByTagName('office').length;
        var arrayOffices = new Array();
        for (j=0;j<=numOffices-1;j++){
            arrayOffices[j] = new objOffice(countryOffices,j)
        }return arrayOffices;
    }
    this.getStatesProvinces = function(){
        var arrayStatesProvinces=new Array();
        for (o=0;o<=this.offices.length-1;o++){
            str=arrayStatesProvinces.toString();
            val=this.offices[o].stateProvince;
            if (str.search(val)==-1 && val!=null){
                arrayStatesProvinces.push(this.offices[o].stateProvince); //<-- fixed a bug here push used instead of assignment
            }//else{alert('duplicate found, not adding to array...')}
        }return arrayStatesProvinces;
    }
    
    // added 051607AP function to search within results for a matching record
    // add 011508AP function to match state as well as the name as some dealers like to branch out to different states/territories
    this.getMyOffice = function(strCompanyName, strStateProvince){
        for (r=0;r<this.numberOfOffices;r++){
            if (strCompanyName==this.offices[r].name){
//                alert('string is: '+string+'\nthis.offices['+r+'] is: '+this.offices[r].name+'\nfound MATCH!')
                return this.offices[r];
            }else('cannot find match '+strCompanyName+'==this.offices['+r+']'+strCompanyName==this.offices[r].name)
        }
    }
    
    this.offices = this.getOffices();
    this.statesProvinces = this.getStatesProvinces();
    this.numberOfOffices = numOffices;
    this.location = country;
    this.country = country;
    this.title = countryOffices.getAttribute('title')
}

// START extending offices object

// get an office
function getOffice(obj_collection,office_name){
//    alert('_____trying to get the office_____')
//    alert('obj_collection.length before finding selection(1)is: '+obj_collection.length)
    for (i=0;i<obj_collection.length;i++){
//        alert('obj_collection['+i+'].name ['+obj_collection[i].name.toLowerCase()+'] is: '+String(obj_collection[i].name.search(office_name.toLowerCase())!=-1)+'\nstring is: '+office_name)
        
        var name=obj_collection[i].name.toLowerCase();
        var office_name=office_name.toLowerCase();
        var selected_office;
        
        if (name.search(office_name)!=-1){
//            alert('found ['+obj_collection[i].name+']!')
            selected_office=obj_collection[i];
        }
    }
//    alert('obj_collection.length after finding selection is: '+obj_collection.length)
    return selected_office,i;
}

// retreive the collection by office type 
function groupByOfficeType(obj_collection,office_type){
    var byCorpOffice = new Array();
    var byDealerOffice = new Array();
    
    for (i=0;i<obj_collection.length;i++){
//        alert('comparing: '+obj_collection[i].officeType+' with '+office_type+'...'+String(obj_collection[i].officeType.search(/corp/gi)!=-1))
        if (obj_collection[i].officeType.search(/corp/gi)!=-1){
            byCorpOffice.push(obj_collection[i]);
        }
        else{
            byDealerOffice.push(obj_collection[i]);
        }
    }    
    if (office_type=="corp"){
        return byCorpOffice;
    }
    else{
        return byDealerOffice;
    }
//    alert('officesByOfficeType: ['+officesByOfficeType+']\n length is:'+officesByOfficeType.length)
}

// sort by company name

// END extending offices object

// START prototype extension for objOffices object
objOffices.prototype.groupByOfficeType=groupByOfficeType;
//objOffices.prototype.writeOffice=writeOffice; --> removed, function writeOffice() has not yet been written
objOffices.prototype.getOffice=getOffice;
// END prototype extension for objOffices object

// this takes the values of record n in the xml node the "getElementsByTagName(tag)[n]"
// this object keeps all its properties in the properties array and
// may be accessed via objOffice.properties[x] where x is a number from 0 to 15
// credits to http://www.javascriptkit.com/javatutors/oopjs2.shtml
function objOffice(x,n){
    
    this.getValue = function(tag){
        if (x.getElementsByTagName(tag)[n].firstChild){
//            alert('x.getElementsByTagName('+tag+')['+n+'].firstChild.nodeValue '+x.getElementsByTagName(tag)[n].firstChild.nodeValue)
            return x.getElementsByTagName(tag)[n].firstChild.nodeValue;
        }else{
//            alert('no value available for '+tag)
            return "";
        }
    }    
    this.getChildValues = function(parentTag,childTag){
        var length=x.getElementsByTagName(parentTag)[n].getElementsByTagName(childTag).length;
        var arrayResults = new Array();
        //alert(length)
        for (i=0;i<=length-1;i++){
            if (x.getElementsByTagName(parentTag)[n].getElementsByTagName(childTag)[i].firstChild)
            arrayResults[i] = x.getElementsByTagName(parentTag)[n].getElementsByTagName(childTag)[i].firstChild.nodeValue;
        }return arrayResults;
    }
    // gather the element values 
    
    this.name = this.getValue('name');
    this.officeType = this.getValue('officeType');
    this.contacts = this.getChildValues('contacts','contact');
    this.mailingAddress = this.getValue('mailingAddress');
    this.address = this.getValue('address');
    this.city = this.getValue('city');
    this.stateProvince = this.getValue('stateProvince');
    this.zipPostal = this.getValue('zipPostal');
    this.country = this.getValue('country');
    this.phoneNumbers = this.getChildValues('phoneNumbers','phone');
    this.emails = this.getChildValues('emails','email');
    this.website = this.getValue('website');
    this.hoursOfOperation = this.getChildValues('hoursOfOperation','hours');
    this.servicesAvailable = this.getChildValues('servicesAvailable','service');
    this.thumbPath = this.getValue('thumbPath');
    this.mapLink = this.getValue('mapLink');
    this.geoAddress = this.getValue('geoAddress');
    this.mapPath = this.getValue('mapPath');
    // save all gathered data into an array, into 'this.properties'
    this.properties = new Array(
        this.name,this.officeType,this.contacts,this.mailingAddress,this.address,this.city,this.stateProvince,this.zipPostal,this.country,
        this.phoneNumbers,this.emails,this.website,this.hoursOfOperation,this.servicesAvailable,
        this.thumbPath,this.mapLink,this.geoAddress,this.mapPath
    )
//    this.showValue = function(num){
//        alert('results: '+this.properties[num])
//    }    
}
function writeToHtml(elementId,textValue,elementNum){
    if ( elementId=='offices' ){ // check if offices are being written
        if ( !document.getElementById(elementNum) ){ //if the design# exists then append
            document.getElementById(elementId).innerHTML += textValue
        }else{ // otherwise overwrite
            document.getElementById(elementId).innerHTML = textValue
        }
    }else{ // for anything else
        document.getElementById(elementId).innerHTML = textValue
    }
}
// checks if object/office is a corporate office
// if so, return "headingCorp"; else exit
function isCorporate(o){
    var style="heading";
    if (o.officeType.search(/corp/gi)!=-1){
        // alert( 'o.officeType.search(/corp/gi) is '+(o.officeType.search(/corp/gi)!=-1?'corporate..':'not corporate..') )
        style="headingCorp";
    }return style;
}
// checks if the office is an international office
// if so, return the country instead of the state/province
// for the header
function isInternational(o){
    var heading;
    if (o.country.search(/canada/gi)==-1 && o.country.search(/usa/gi)==-1){
        heading=o.country;
    }else{
        heading=o.stateProvince;
    }
    return heading;
}
// checks if there is a city, if so, a comma is added to the end of the string
function isCityPresent(o){
    var str=o.city;
    if (str){
        str=str+',';
    }return str;
}
// credits to http://www.mediacollege.com/internet/javascript/date-time/
// credits to http://www.webdevelopersnotes.com/tips/html/formatting_time_using_javascript.php3
function getDateTime(){
    var date = new Date();
    var d  = date.getDate();
    var day = (d < 10) ? '0' + d : d;
    var m = date.getMonth() + 1;
    var month = (m < 10) ? '0' + m : m;
    var yy = date.getYear();
    var year = (yy < 1000) ? yy + 1900 : yy;
    var submitDate=day + "-" + month + "-" + year;

    var suffix = "";
    var d = new Date();
    var curr_hour = d.getHours();
    var curr_min = d.getMinutes();
    
    suffix=(curr_hour < 12)?suffix = "AM":suffix = "PM";
    curr_hour=(curr_hour == 0)?curr_hour = 12:curr_hour;
    curr_hour=(curr_hour > 12)?curr_hour = curr_hour - 12:curr_hour;
    curr_min = curr_min + "";
    curr_min=(curr_min.length == 1)?curr_min = "0" + curr_min:curr_min;
    
    var submitTime=curr_hour + ":" + curr_min + " " + suffix;
    
    document.getElementById('Date').value=submitDate;
    document.getElementById('Time').value=submitTime;
//    document.getElementById('Browser').value=BrowserDetect.browser+' '+BrowserDetect.version;
}
// to detect browsers credits to: http://www.quirksmode.org/js/detect.html
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();