//
//  Esoteric javascript coding for Accounting Issue home page.
//
//  Call relevent function for each area of home page - Dependent on Tab selected - On initial load the paramenters passed to this function will be set to 1.

//  Example of code calling this script file:

//  <script type="text/javascript" src="http://www.accountingissue.info/hpLoadControl.js#obj1/ABC/obj2/XYZ/obj3/abc">


//  1) The ID attribute has been removed. Even without the ID attribute there is still a simple way to reference the script element. The trick is to take advantage 
//     of the fact that as the browser is rendering the page, it executes JS code immediately when encountered. As a result, if the code in your JS file queries the DOM, 
//     the last script element in the DOM is a self-reference (i.e. a reference to the script element that loaded the code being executed). Thus, using 
//     document.getElementsByTagName("script") and referencing the last element in the array, provides an easy way to get the current script reference.

//  2) The standard querystring separator "?" has been replaced by "#". This is not necessary, but something I did for semantic reasons. To overcome the "&" entity issue, 
//     I used a slash ("/") character for separating not only key-value pairs, but keys and values too. The reason for this will become evident in a bit, but since I 
//     modified the querystring to something non-standard, I felt it was important to also remove the "?" separator which is a prefix for querystring. Instead, I used a 
//     hash ("#") character which is a pointer to a document fragment and does not have any semantic value in the context of a JS script URL. (In fact the JS URL hash 
//     technique is a common way to pass data in cross-domain XMLHttp requests for this reason and also because it does not cause a page re-load.)

//  3) Key-Value pairs. The last change I made is to use a path-based approach to key-value pairs instead of Key=Value format. I did this because it is a common technique 
//     in RESTful URL's, is easier to read and much simpler to parse. In fact, using a single "for..." loop, it becomes a trivial task to create an associative array of 
//     all the parameters for ready reference.


var tabParams = getTabParams();

tabParam1 = (tabParams["obj1"]);
tabParam2 = (tabParams["obj2"]);
tabParam3 = (tabParams["obj3"]);


//document.write("hpLoadControl RETURNED Params -  tabParam1 = " + tabParam1 + "  tabParam2 = " + tabParam2 + "  tabParam3 = " + tabParam3 + "<br />");

function getTabParams()
{	
	var tabScriptTags = document.getElementsByTagName("script");
	// This code is assumed to be in a file so the "src" attribute	
	// is guaranteed to be present...no error-checking is needed	
	var tabParamFrags = tabScriptTags[tabScriptTags.length-1].src.split("#hpLoadControl=");
	
	//document.write("hpLoadControl Params = " + tabParamFrags + "<br />");
	
	var ftabParams=[];
	var tabParamRaw = [];

	if (tabParamFrags.length > 1)
	{	    
	    tabParamRaw = tabParamFrags[1].split("/");
   	    if (tabParamRaw.length >= 2)
	    {	    	
		for(var param=0;param<tabParamRaw.length;param+=2)
	            ftabParams[tabParamRaw[param]] = (tabParamRaw.length >= param + 1 ? unescape(tabParamRaw[param+1]) : null);
    	    }
	}
	return(ftabParams);
}



//
// This code controls the functions that are called to home build page - (tabParam1 = The tab selected 1 thru 4) 
//									 (tabParam2 = Color Style No associate with tab) 
//									 (tabParam3 = Color Style No associate with previous tab selection)  
// This function controls the main processing
// ** M A I N    P R O C E S S I N G    C O N T R O L
//
//      Note: For site preferences the default processing values are always the same and thus no variable parameters are required.
//      if this changes section above should be replicated for site preferences but using all different variable names and the variables 
//      passed as per the tab function

// 1. Set up site preferences window
if  (tabParam1 == 2) {
	//Load home page with membership form diplayed open - This will occur when Join Now button clicked from page other than home.
	getSITEPREFdata(1,91,0);
	//Note: Set tabParam1 = 1 to ensure page opens with business tab selected. 
	tabParam1 = 1;
}
else {
	//Normal page load  
	getSITEPREFdata(1,99,0);	
} //End if


// 2. Now set up site tab window  
Tab(tabParam1,tabParam2,tabParam3);

// 3. Now get newsletter sign-up form
getNewsletterData(1,1,0);











function Tab(tabParam1,tabParam2,tabParam3) {
	
  //document.write("HP LOAD CONTROL -   STR = " + tabParam1 + "  ST2 = " + tabParam2 + "  STR3 = " + tabParam3 + "<br />");	
	

  //Update style sheet
  var newfilename = "site-styles-colors"+tabParam2+".css";
  var oldfilename = "site-styles-colors"+tabParam3+".css";
  var filetype = "css";
  replacejscssfile(oldfilename, newfilename, filetype);

//
//***** Note: Now replaced tabParam3 is the new color scheme so set tabParam3 = tabParam2 ******  
  tabParam3 = tabParam2;


  var xmlHttp;
  tabParam1 = String(tabParam1);

  //Update logo image at top of page
  imgid = "logo";
  imgname = "images/accounting-issue"+tabParam2+".gif";
  updateImage(imgid, imgname);

  //Update contents of feature box
  FeatureBox(tabParam1,tabParam2,tabParam3);
}


// *************************************************************************
// Fuctions below are called from main function above or directly from page
// *************************************************************************


// 1 . This code updates the style sheet in the <head> part of the page

// ****** NB: These lines are for parameter example only, and NOT coding commented out!  ******* 
// replacejscssfile("oldscript.js", "newscript.js", "js") //Replace all occurences of "oldscript.js" with "newscript.js"
// replacejscssfile("oldstyle.css", "newstyle", "css") //Replace all occurences "oldstyle.css" with "newstyle.css"


function replacejscssfile(oldfilename, newfilename, filetype) {
  var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
  var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
  var allsuspects=document.getElementsByTagName(targetelement)
  for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
    if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
       var newelement=createjscssfile(newfilename, filetype)
       allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
    }
  }
}

// Note: This fuction is called by one directly above! 
function createjscssfile(newfilename, filetype) {
  if (filetype=="js"){ //if filename is a external JavaScript file
     var fileref=document.createElement('script')
     fileref.setAttribute("type","text/javascript")
     fileref.setAttribute("src", newfilename)
  }
  else if (filetype=="css"){ //if filename is an external CSS file
     var fileref=document.createElement("link")
     fileref.setAttribute("rel", "stylesheet")
     fileref.setAttribute("type", "text/css")
     fileref.setAttribute("href", newfilename)
  }
  return fileref
}




// 2. This code updates the Accounting Issue logo in the first row of the home page  
function updateImage(imgid, imgname) {
  var image = document.getElementById(imgid);
  image.src = imgname;
}


// 3. This code updates/builds the feature box window.
function FeatureBox(tabParam1,tabParam2,tabParam3) { 
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		return;
	}
	
	switch (tabParam1)
		{
		case "1":
			var url="php/tab1-color-menu-hp.php";
			break;
		
		case "2":
			var url="php/tab2-color-menu-hp.php";
			break;
		
		case "3":
			var url="php/tab3-color-menu-hp.php";
			break;
		
		case "4":
			var url="php/tab4-color-menu-hp.php";
			break;
		
		default:
			var url="php/tab1-color-menu-hp.php";
			document.write("invalid tabParam1 hpLoadControl = ");
			document.write(tabParam1);
	} //End switch
	url=url+"?hpLoadControl="+tabParam1+"/"+tabParam2+"/"+tabParam3;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=stateChangedFeatureBox; 
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}


function stateChangedFeatureBox() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 document.getElementById("hpFeatureBox").innerHTML=xmlHttp.responseText 
 } 
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

//*********************************************************************************************************************************************************
function getSITEPREFdata(prefParam1,prefParam2,prefParam3) {
	var xmlHttp2;
	prefParam1 = String(prefParam1);
	prefParam2 = String(prefParam2); 
	prefParam3 = String(prefParam3); 
	
	showSITEPREFdata(prefParam1,prefParam2,prefParam3);
}





//Called functions below this line

function showSITEPREFdata(prefParam1,prefParam2,prefParam3,prefParam4)
{
	xmlHttp2=GetXmlHttpObject2()
	if (xmlHttp2==null) {
		alert ("Browser does not support HTTP Request")
		return
	}
	
	str1 = String(prefParam1);
	str2 = String(prefParam2);
	str3 = String(prefParam3);
	str4 = String(prefParam4);
	
//	if  (str2 == 91) {
//		listAttributes();	
//	}

	switch (str2)
		{
		case "100":
			var x=document.getElementById("membersFRM1");
				
			for (var i=0;i<=1;i++)
				{
				switch(i)
					{
					case 0:
						sie=x.elements[i].value;
						break;
					default:
						sip=x.elements[i].value;
				} //End switch
			} //End loop
		
			params = "t="+str1+"&pv1="+str2+"&pv2="+str3+"&pv3="+str4+"&sie="+sie+"&sip="+sip;
			break;
		
		case "110":
		case "115":
			var x=document.getElementById("membersFRM2");
				
			for (var i=0;i<=3;i++)
				{
				switch(i)
					{
					case 0:
						email=x.elements[i].value;
						break;
					case 1:
						cemail=x.elements[i].value;
						break;						
					case 2:
						contact=x.elements[i].value;
						break;						
					default:
						country=x.elements[i].value;
				} //End switch
			} //End loop		
		
			params = "t="+str1+"&pv1="+str2+"&pv2="+str3+"&pv3="+str4+"&email="+email+"&cemail="+cemail+"&contact="+contact+"&country="+country;
			break;

		default:
			params = "t="+str1+"&pv1="+str2+"&pv2="+str3+"&pv3="+str4;
	} //End switch

	//Browse existing SITEPREFs and control of other options - This is the main screen
	params = encodeURIComponent(params);
	
	var url="http://www.accountingissue.info/php/auth/get-site-preferences-data1.php?" + params;


	//url=url+"?sitePreferences="+prefParam1+","+prefParam2+","+prefParam3
	url=url+"&sid="+Math.random()
	xmlHttp2.onreadystatechange=prefStateChanged 
	xmlHttp2.open("GET",url,true)
	xmlHttp2.send(null)
}





function prefStateChanged() 
{ 
if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete")
 { 
 document.getElementById("siteprefData").innerHTML=xmlHttp2.responseText 
 } 
}

function GetXmlHttpObject2()
{
var xmlHttp2=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp2=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp2=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp2=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp2;
}



function getNewsletterData(newsParam1,newsParam2,newsParam3) {
	var xmlHttp3;
	newsParam1 = String(newsParam1);
	newsParam2 = String(newsParam2); 
	newsParam3 = String(newsParam3); 
	showNewsletterData(newsParam1,newsParam2,newsParam3);
}


function showNewsletterData(newsParam1,newsParam2,newsParam3)
{
//	document.write("Show News Letter");	
	xmlHttp3=GetXmlHttpObject3()
	if  (xmlHttp3==null) {
		alert ("Browser does not support HTTP Request")
		return
	}
	
	newsParam1 = String(newsParam1);
	newsParam2 = String(newsParam2);
	newsParam3 = String(newsParam3);


	var url="http://www.accountingissue.info/php/auth/newsletter-insert-confirm-email.php"
	
	if  (newsParam2==1) { 
		url=url+"?t="+newsParam1+"&pv1="+newsParam2+"&pv2="+newsParam3;
	}
	else {
		var x=document.getElementById("newsletterFRM");
		
		for (var i=0;i<=3;i++)
			{
			switch(i)
				{
				case 0:
					email=x.elements[i].value;
					break;
				case 1:
					cemail=x.elements[i].value;
					break;
				case 2:
					contact=x.elements[i].value;
					break;	
				default:
					referral=x.elements[i].value;
			}
		}
		//Do here to prevent transaction abend
		
		url=url+"?t="+newsParam1+"&pv1="+newsParam2+"&pv2="+newsParam3+"&email="+email+"&cemail="+cemail+"&contact="+contact+"&referral="+referral;
	}

	url=url+"&sid="+Math.random()
	xmlHttp3.onreadystatechange=newsletterStateChanged 
	xmlHttp3.open("GET",url,true)
	xmlHttp3.send(null)
}





function newsletterStateChanged() 
{ 
if (xmlHttp3.readyState==4 || xmlHttp3.readyState=="complete")
 { 
 document.getElementById("newsletterAREA").innerHTML=xmlHttp3.responseText 
 } 
}

function GetXmlHttpObject3()
{
var xmlHttp3=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp3=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp3=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp3=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp3;
}


//This is used for debugging forms
function listElements()
	{
	var x=document.getElementById("membersFRM2");
	var max_items = x.length;
	var item_count = -1;	
	
	for (var i=0;i<x.length;i++)
//	for (var i=0;i<=14;i++)
		{
		item_count++;	
		document.write(x.elements[i].name + " - " + x.elements[i].value);
		document.write("<br />");
	}
}



//This is used for debugging forms
function listAttributes()
	{
	var totalattributes=0;
	for (i=0;i<document.getElementById("signInButton").attributes.length;i++){
	//if attribute is user defined
		if (document.getElementById("signInButton").attributes[i].specified) {
			totalattributes++
			v = document.getElementById("signInButton").attributes[i].value;
			document.write("<br />" + v);
		}
	}
	
		
		
		
//	var x=document.getElementById("signInButton");
//	var max_attrib = x.attributes.length;
//	var item_count = -1;	
//	
//	for (var i=0;i<x.attributes.length;i++)
////	for (var i=0;i<=14;i++)
//		{
//		document.write(x.elements.name + " - " + x.attributes[i].value);
//		document.write("<br />");
//	}
}


