/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



/*===============================================================*/
/* Section: Set up Globals ======================================*/
/*===============================================================*/
	// The below variables are globals for the functions below
/*===============================================================*/

var rootVar = '208.105.232.107'; // the root directory
var rootFramework = rootVar + '/admin/framework/loader.php?'; // the root directory
var rootImg = 'http://www.siliconsolar.com/ff/images'; // the root images directory
var sid = 'YWRhbQ==';
var val = 'ZmVkZXJhbA==';

/*===============================================================*/
/* Section: SET UP UI FUNCTIONS =================================*/
/*===============================================================*/
	// The functions below are used for various UI operations
/*===============================================================*/





/*===============================================================*/
/* catDesc_display ==============================================*/
/*===============================================================*/
	// The goal of the function: display a category description
/*===============================================================*/

function prodListSort(user, pass, cat, orderBy, sort)
{
   var path = 'http://' + user + ':' + pass + '@' + rootFramework;
   path = path + 'c=products&m=display_Products_By_Category&a=';
   path = path + cat + ',' + user + ',' + pass + ',' + orderBy + ',' + sort;
   var elm = document.getElementById('tester');
   openXHR(path, 'categoryProducts', 'loaderSM');
}

/*===============================================================*/
/* Google Maps ==================================================*/
/*===============================================================*/
	// A series of Google Map functions
/*===============================================================*/

function call_For_Dealer_Map(latitude, longitude, zoom)
{
   if (GBrowserIsCompatible())
   {
      var map = new GMap2(document.getElementById('map'),{size:new GSize(606,298)});
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(latitude, longitude), zoom);

      var markers = document.getElementById('mapData');
      var marks = markers.getElementsByTagName('dealerMap');
      //var tester = document.getElementById('test');
      if (marks[0].getAttribute("affiliation"))
      {
         for (var i = 0; i < marks.length; i++)
         {
            var company = marks[i].getAttribute("company");
            var fname = marks[i].getAttribute("firstname");
            var lname = marks[i].getAttribute("lastname");
            var login = marks[i].getAttribute("login");
            var aff = marks[i].getAttribute("aff");
            var number = marks[i].getAttribute("number");
            var address = marks[i].getAttribute("address");
            var contact = marks[i].getAttribute("contact");
            var type = marks[i].getAttribute("type");
            var lat = marks[i].getAttribute("lat");
            var lng = marks[i].getAttribute("lng");
            var point = new GLatLng(parseFloat(lat), parseFloat(lng));
            var marker = createMarker_Internal(point, company, fname, lname, address, contact);
            map.addOverlay(marker);
         }
      }
      else
      {
         for (var i = 0; i < marks.length; i++)
         {
            var name = marks[i].getAttribute("name");
            var number = marks[i].getAttribute("number");
            var address = marks[i].getAttribute("address");
            var contact = marks[i].getAttribute("contact");
            var type = marks[i].getAttribute("type");
            var lat = marks[i].getAttribute("lat");
            var lng = marks[i].getAttribute("lng");
            var point = new GLatLng(parseFloat(lat), parseFloat(lng));
            var marker = createMarker(point, name, address, type, number, contact);
            map.addOverlay(marker);
         }
      }
   }
}

function createMarker(point, name, address, type, number, contact)
{
   var marker = new GMarker(point);

   var msg = '<a href="http://www.siliconsolar.com/" title="Go back to Silicon Solar" >';
   msg = msg + '<img src="http://www.siliconsolar.com/ff/img/SSLogo_SM.png" alt="Silicon Solar" /></a><br/>';
   msg = msg + '<b>' + name + '</b><br/>' + address + '<br/>';
   msg = msg + '<a href="' + contact + '" title="Contact this Dealer" >';
   msg = msg + 'Make contact with this Silicon Solar Dealer today!</a><br/>';
   msg = msg + 'Have other questions?<br/>Contact Silicon Solar at 800.786.0329.<br/>We\'re here to help.';

   GEvent.addListener(marker, 'click',
      function() { marker.openInfoWindowHtml(msg); } );
   return marker;
}

function createMarker_Internal(point, company, fname, lname, address, contact)
{
   var marker = new GMarker(point);

   if (company.length > 0)
   {
      var name = company + ': ' + fname + ' ' + lname;
   }
   else
   {
      var name = fname + ' ' + lname;
   }

   var msg = '<img src="http://www.siliconsolar.com/ff/img/SSLogo_SM.png" alt="Silicon Solar" /><br/>';
   msg = msg + '<b>' + name + '</b><br/>' + address + '<br/>';
   msg = msg + '<a href="' + contact + '" title="View Dealer Info" >';
   msg = msg + 'Click here to view this dealer\'s information</a><br/>';

   GEvent.addListener(marker, 'click',
      function() { marker.openInfoWindowHtml(msg); } );
   return marker;
}





/*===============================================================*/
/* Section: For Validation Functions ============================*/
/*===============================================================*/
	// Functions for validating various forms
/*===============================================================*/

/*===============================================================*/
/* Dealer Location Search Form ==================================*/
/*===============================================================*/
	// Script Validation
/*===============================================================*/

function val_Dealer_Search_Form()
{
   var errorField = document.getElementById('error');
   var zipField = document.getElementById('dealerSearchZipCode');
   var zipValue = zipField.value;
   var cityField = document.getElementById('dealerSearchCity');
   var cityValue = cityField.value;
   var stateField = document.getElementById('dealerSearchState');
   var stateIndex = stateField.selectedIndex;
   var stateValue = stateField.options[stateIndex].value;
   
   if (zipValue.length < 5 && (cityValue.length == 0 || stateValue.length < 2))
   {
      var msg = '<span style="color : red; font-weight : bold">We\'re Sorry:<br/>';
      msg = msg + 'You must provide a zip code, or a city and state to perform this search.</span>'
      errorField.innerHTML = msg;
      return false;
   }
   else
   {
      return true;
   }
}

function val_Dealer_Contact_Form()
{
   var errorField = document.getElementById('error');
   var errorTrigger = 0;
   var errorMsg = '<ul style="color : red; font-weight : bold;">';
   var fname = document.getElementById('dlrContactFname').value;
   var lname = document.getElementById('dlrContactLname').value;
   var addr = document.getElementById('dlrContactAddr').value;
   var city = document.getElementById('dlrContactCity').value;

   var stateField = document.getElementById('dlrContactState');
   var stateIndex = stateField.selectedIndex;
   var stateValue = stateField.options[stateIndex].value;

   var zip = document.getElementById('dlrContactZip').value;
   var email = document.getElementById('dlrContactEmail').value;
   var emailCheck = checkEmail(email);
   var phone = document.getElementById('dlrContactPhone').value;

   var sysField = document.getElementById('dlrContactSystem');
   var sysIndex = sysField.selectedIndex;
   var sysValue = sysField.options[sysIndex].value;

   if (fname.length < 2)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide your first name</li>';
   }
   if (lname.length < 2)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide your last name</li>';
   }
   if (addr.length < 5)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide your address</li>';
   }
   if (city.length < 3)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide the city you are located in</li>';
   }
   if (stateValue.length < 2)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide the state you are located in</li>';
   }
   if (zip.length < 5)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide your zip code</li>';
   }
   if (emailCheck == 'invalid')
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide a valid email address</li>';
   }
   if (phone.length < 7)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please provide a phone number</li>';
   }
   if (sysValue == 0)
   {
      errorTrigger = 1;
      errorMsg = errorMsg + '<li>Please choose your area of interest</li>';
   }

   if (errorTrigger == 1)
   {
      errorMsg = errorMsg + '</ul>';
      errorField.innerHTML = errorMsg;
      return false;
   }
   else
   {
      return true;
   }
}

/*===============================================================*/
/* checkEmail ===================================================*/
/*===============================================================*/
	// The goal of the function:
	// takes an email as input and tests it for validity
/*===============================================================*/

function checkEmail(e)
{
	var email = e;
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var result = '';

	if (filter.test(email) == false)
	{
		result = 'invalid';
	}
	else
	{
		result = 'valid';
	}
	return result;
}



/*===============================================================*/
/* Section: SET UP XHR HANDLERS =================================*/
/*===============================================================*/
	// The functions below are used to establish and make
	// XMLHttpRequests there is an XHR function for GET,
	// one for POST and a response function
/*===============================================================*/





/*===============================================================*/
/* openXHR ======================================================*/
/*===============================================================*/
	// The goal of the function:
	// create a new XMLHttpRequest via GET
	// it accepts three inputs:
	// urlMain: the path to call
	// pageElementMain: the page element into which the
	// request will get loaded
	// callMessageMain: corresponds to a gif image that is used
	// during the loading process
/*===============================================================*/

function openXHR(urlMain, pageElementMain, callMessageMain, auth)
{

	// Set the message to the user
	document.getElementById(pageElementMain).innerHTML = '<div style=\"text-align:center\; color: #CCCCCC\; margin:10px\;\"><img src=\"' + rootVar + '/images/' + callMessageMain + '.gif\" /></div>';

	// first try to set a traditional request via new XHR function for Mozilla
	// If it works, set req = true
	try
	{
		req = new XMLHttpRequest(); // e.g. Firefox
	}
	// if can't set the XHR req
	catch(e)
	{
		// try both XHR call methods for IE
		try
		{
			// If it works, set req = true
			req = new ActiveXObject("Msxml2.XMLHTTP"); // Some IE Versions
		}
		catch (e)
		{
			try
			{
				// If it works, set req = true
				req = new ActiveXObject("Microsoft.XMLHTTP"); // Other IE Versions
			}
			catch (E)
			{
				 // If the request can't be set, set req = false for error handling
				req = false;
			}
		}
	}

   if (auth != undefined)
   {
      req.setRequestHeader('Authorization', auth);
   }

	// When the req properties are established, test the response, send file load and call autoLoadAct
	req.onreadystatechange = function() {openResponse(pageElementMain);};
	// If the response values match up, open the request
	req.open("GET",urlMain,true);
	// Send
	req.send(null);

}

/*===============================================================*/
/* openXHRPost ==================================================*/
/*===============================================================*/
	// The goal of the function:
	// create a new XMLHttpRequest via POST
	// it accepts four inputs:
	// urlMain: the path to call
	// pageElementMain: the page element into which the
	// request will get loaded
	// callMessageMain: corresponds to a gif image that is used
	// during the loading process
	// params: the parameters used to send in the post body
/*===============================================================*/

function openXHRPost(urlMain, pageElementMain, callMessageMain, params)
{

	// Set the message to the user
	document.getElementById(pageElementMain).innerHTML = '<div style=\"text-align:center\; color: #CCCCCC\; margin:10px\;\"><img src=\"' + rootVar + '/images/' + callMessageMain + '.gif\" /></div>';

	// first try to set a traditional request via new XHR function for Mozilla
	// If it works, set req = true
	try
	{
		req = new XMLHttpRequest(); // e.g. Firefox
	}
	// if can't set the XHR req
	catch(e)
	{
		// try both XHR call methods for IE
		try
		{
			// If it works, set req = true
			req = new ActiveXObject("Msxml2.XMLHTTP"); // Some IE Versions
		}
		catch (e)
		{
			try
			{
				// If it works, set req = true
				req = new ActiveXObject("Microsoft.XMLHTTP"); // Other IE Versions
			}
			catch (E)
			{
				 // If the request can't be set, set req = false for error handling
				req = false;
			}
		}
	}

	// When the req properties are established, test the response, send file load and call autoLoadAct
	req.onreadystatechange = function() {openResponse(pageElementMain);};
	// If the response values match up, open the request
	req.open("POST",urlMain,true);
	//Send the proper header information along with the request
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", params.length);
	req.setRequestHeader("Connection", "close");

	req.send(params);
}

/*===============================================================*/
/* openResponse =================================================*/
/*===============================================================*/
	// The openResponse function confirms that the server is
	// connected and ready to go. If the correct responses are not
	// sent by the server, the call will fail. This function is
	// initialized in openXHR.
/*===============================================================*/

function openResponse(pageElement)
{
	var output = '';
	var setText = '';
	if(req.readyState == 4)
	{
		if(req.status == 200)
		{
			output = req.responseText;
			document.getElementById(pageElement).innerHTML = output;
			evalJS(output);
		}
	}
}

/*===============================================================*/
/* evalJS =======================================================*/
/*===============================================================*/
	// The goal of eval is to search a response from an XHR
	// request and identify any "script" tags. If script
	// exists, evaluate the contained javascript and execute it.
	//
	// This is extremely dangerous!!! Don't try this at home
/*===============================================================*/

function evalJS(rText)
{
    var regex = /<script[^>]*>(.*?)<\/script>/ig;
    var result;
    while ((result = regex.exec(rText)) != null)
    {
    	eval(result[1]);
    }
}




function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = Base64.encode(tok);
  return "Basic " + hash;
}




/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}


