// JavaScript Document
// Written by Michael DuBois for Farmscape, LLC
// Description: Adds a hash string to the URL when a page is loaded into the iframe, HAL. Then, the script reloads the page in HAL based on the hash entered--thus, allowing visitors to bookmark and link to the webpage despite it's AJAX-style content loader.
//Pages coded in PHP
phpext = new Array()
   phpext[0] = "home"; 
   phpext[1] = "blog";
function setHash(){
	recentHash = window.location.hash;
}
function loadPage(HASH) {
	if(window.location.pathname=='index.html'){
		 window.location.hash = HASH;
		 initializeStateFromURL();
	}
	else{
		window.location = "/#"+HASH
	}
}
function pollHash() {
	if (window.location.hash==recentHash) {
		   return; // Nothing's changed since last polled.
	}
 	// URL has changed, update the UI accordingly.
     recentHash = window.location.hash;
     initializeStateFromURL();
   }
function initializeStateFromURL() {
	var hashval = window.location.hash.substr(1);
	if(hashval==''){
		var file = "home.php?ajax=1";
	}
	else{
		hashdir = hashval.split(/\//);
		hashdirlength = hashdir.length;
		if(hashdir[hashdirlength-1]==''){
			hashdir.length=hashdirlength-1;
			hashdirlength = hashdir.length;
		}
		if(hashdirlength>=2){
			if(hashdir[0]=='blog' && hashdir[1]!=''){
				if(IsNumeric(hashdir[1])){
					var file = "entry.php?id="+hashdir[1]+"&ajax=1";
				}
				else if(hashdir[1].match(/p[1-9][1-9]*/)){
						var pageNum = hashdir[1].substr(1);
						var file = 'blog.php?page=' + pageNum + "&ajax=1";
				}
				else if(hashdir[1].match(/archives/) && hashdir[2].match(/(([a-zA-Z]+)-)?([0-9]+)/)){
					var archive_date = hashdir[2].split(/-/);
					if(archive_date[1]){
						var archive_month = archive_date[0];
						var archive_year = archive_date[1];
					}
					else{
						var archive_year = archive_date[0];
						var archive_month='';
					}
					var pageNum = '';
					if(hashdirlength>=4){
						if(hashdir[3].match(/p[1-9][1-9]*/)){
							var pageNum = hashdir[3].substr(1);
						}
					}
					var file = 'blog.php?page=' + pageNum + "&year=" + archive_year + "&month=" + archive_month + "&ajax=1";
				}
			}
			else if(hashdir[0]=='faq' && hashdir[1]!=''){
				var file = "faq.php?tag="+hashdir[1]+"&ajax=1";
			}
			else{
				var file = 'error.php?error=url';
			}
		}
		else{
			var file = window.location.hash.substr(1)+".php?ajax=1";
		}
	}
	recentHash = window.location.hash;
	grabFile(file);
	//var objFrame=document.getElementById("HAL");
	//objFrame.src = window.location.hash.substr(1)+".html";
	//var encodedState = base64(json(state));
	//var newLocation = oldLocationWithoutFragment + "#" + encodedState;
	//document.location = newLocation;
	//document.location.replace(newLocation);
}  
function grabFile(file,results) {
	var request = getHTTPObject();
	request.onreadystatechange = function() {
		parseResponse(request,file,results);//this is what happens once complete
	}
	request.open("GET",file,true);
	request.send(null);
}
/*Once the request state is complete and the file exists, it grabs the results
			 * div, and inserts the response text and innerHTML.
			 */
function parseResponse(request,file,results) {
	if(!results){
		var results = document.getElementById("content");
	}
	if(request.readyState == 4){
		if(request.status == 200 || request.status == 304){
			results.innerHTML = request.responseText;
			var re_title = new RegExp("<title *>[\n\r\s]*[^<>]*[\n\r\s]*</title *>", "gmi");
        	// page text
       		var pagetitle = String(re_title.exec(request.responseText));
			if (pagetitle != null){
				var newtitle = pagetitle.replace(/<[^<>]+>/gmi,"");
				document.title = newtitle;
        	}
        	else{//no title
			document.title = "Farmscape Gardens";
    		}
			if(file){
				pageTracker._trackPageview(file);
				try{ runSlideshow('0','home-slideshow-container','home-slideshow-caption','home-slideshow-nav');}
				catch(err){}
				var NewScript=document.createElement('script');
				NewScript.src="http://w.sharethis.com/button/buttons.js";
				document.body.appendChild(NewScript);
				stLight.options({publisher:'cb09d53a-a23f-474f-a02b-b55bf12f5bf4'});
			}
		} 
		else {
				alert('Error: PC load letter.');
			//var objFrame=document.getElementById("HAL");
			//objFrame.src = window.location.hash.substr(1)+".html";
			//changeContent();
		}
	}
}
function getHTTPObject() {
	var xhr = false;//set to false, so if it fails, do nothing
	if(window.XMLHttpRequest) {//detect to see if browser allows this method
		var xhr = new XMLHttpRequest();//set var the new request
	} else if(window.ActiveXObject) {//detect to see if browser allows this method
		try {
			var xhr = new ActiveXObject("Msxml2.XMLHTTP");//try this method first
		} catch(e) {//if it fails move onto the next
			try {
				var xhr = new ActiveXObject("Microsoft.XMLHTTP");//try this method next
			} catch(e) {//if that also fails return false.
				xhr = false;
			}
		}
	}
	return xhr;//return the value of xhr
}
function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}
function IsNumeric(sText){
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}
