//
// Copyright 2009 Digital Propulsion Labs
// Written by Brian McGuire
//

var debug = false;
var iViews;
var legacy_mode = false;
var gAlbum;
var emailPat = /^(.+)@(.+)(\.[a-z]+){1,2}$/;
var isGlobal = true;

function validate(strInp,regPatt)
{
	return (strInp.match(regPatt) == null) ? false : true;
}

// http://soleone.org/nuclearwinter/?donationcomplete
function initPage()
{
	iViews = new downloadProcess();
	var locSrch = window.location.search;
	if ((debug || locSrch.indexOf("donationcomplete") > 0) && !legacy_mode)
	{
		if (locSrch.length > 0)
		{
			lv = locSrch.substr(1,locSrch.length);
			if (eval("iViews."+lv)) actionView(lv);
		}
	}
}

function __initdownload(a)
{
	gAlbum = a;
	actionView('step1');
}

function __postback()
{
	var whatis, requrl;
	var args = __postback.arguments;
	if (args.length > 1)
	{
		var onit = args[0];		// status code
		var htreq = args[1];	// http request handle
		whatis = args[2];	// action
	}
	else
	{
		whatis = args[0];
	}

	if (!htreq) requrl = "index.php?__postback="+whatis;

	if (legacy_mode)
	{
		var fs = window.location.search.split("&")[0];
		fs = fs.substr(fs.indexOf("=")+1, fs.length);
		//alert('postback;'+whatis+' :: '+fs);
		getCtrlHandle("action").value = whatis;
		getCtrlHandle(fs).submit();
		return true;
	}

	if (whatis == "createsession")
	{
		if (args.length == 1)
		{
			eaddr = getCtrlHandle("email").value;
			if (validate(eaddr,emailPat))
			{
				simpleXMLRequest(requrl+"&e="+eaddr, "__postback", whatis);
			}
			else
			{
				alert("Please enter a valid email address to contine with the download.");
				return false;
			}
		}
		else if (onit && onit == "error")
		{
			alert("an error occured, darn.  Please try again later");
		}
		else if (onit && onit == "success")
		{
			reptxt = htreq.responseText;
			if (reptxt.indexOf("successful") >= 0 || reptxt.indexOf("email_exists") >= 0)
			{
				actionView('step2');
			}
			else if (reptxt.indexOf("email_allowed") >= 0)
			{
				//actionView('download');
				__postback('startdownload');
			}
			else if (reptxt.indexOf("maximum") >= 0)
			{
				alert("You've reached the maximum allowed downloads for the album, please make a donation if you'd like to download again.");
				actionView('step2');
			}
			else
			{
				alert("Oops, seems we've had an unexpected response.  Please try restarting the download process. "+(debug?"("+htreq.responseText+")":""));
			}
		}
	}
	else if (whatis == "download")
	{
		// redirect to download free album zip
		if (args.length == 1)
		{
			donamt = parseInt(getCtrlHandle("amount").value);
			if (donamt > 0)
			{
				// send to paypal
				alert("You will now be redirected to PayPal to complete your donation.");
				window.location = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9478647";
			}
			else
			{
				simpleXMLRequest(requrl, "__postback", whatis);
			}
		}
		else if (onit && onit == "error")
		{
			alert("An error occured, darn.  Please try again later");
		}
		else if (onit && onit == "success")
		{
			if (htreq.responseText.indexOf("email_sent") >= 0)
			{
				//alert(htreq.responseText);
				actionView('download');
			}
			else
			{
				alert("Oops, seems we've had an unexpected issue sending the email.  Please try restarting the download process. "+(debug?"("+htreq.responseText+")":""));
			}
		}
	}
	else if (whatis == "startdownload")
	{
		if (args.length == 1)
		{
			eaddr="";
			if (getCtrlHandle("donemail")) eaddr = getCtrlHandle("donemail").value;
			simpleXMLRequest(requrl+"&e="+eaddr, "__postback", whatis);
		}
		else if (onit && onit == "error")
			alert("Oh no, it seem an error occured.  Please try again later");
		else if (onit && onit == "success")
		{
			if (htreq.responseText.indexOf("redirect") >= 0)
			{
				window.location = htreq.responseText.substr(htreq.responseText.indexOf(":")+1,htreq.responseText.length);
				//"<?=$GLOBALS["site_root"]?>download.php?f=sole_nuclearwinter_192k.zip&fc=0000_nuclearwinter_192k.zip";
			}
			else if (htreq.responseText.indexOf("maximum") >= 0)
			{
				alert("Whoops, you've already downloaded the album.  Please support our efforts by donating and you can download again.");
			}
			else
			{
				alert("You do not have access to download the file.");
			}
		}
	} else {
		if (debug) alert("no idea...");
	}

	return true;
}

function downloadProcess()
{
	// local vars
	this.title = "Nuclear Winter";
	this.activeview = null;

	// Step 1
	this.step1 = new iView;
	this.step1.title = "Download "+this.title+" - Step 1";
	//this.step1.content = "Thanks for your interest in the album,<br>please enter your email address to contiue.<br><br><div id=''><input type=text name='email' id='email'> <input type='button' name=step1_cont id=step1_cont value='Continue' onclick=\"__postback('createsession');\"></div><p>If you've already made a donation for the album <a href='#donationcomplete' onclick=\"actionView('donationcomplete');\">click here</a>";
	this.step1.width = "400px;"
	this.step1.content = "xml:./content/nuclearwinter.xml#step1";
	//<br><br>NOTE: Make sure you use a valid email<br>address, otherwise you won't receive the email to download "+title+"

	// Step 2
	this.step2 = new iView;
	this.step2.title = "Download "+this.title+" - Step 2";
	this.step2.width = "800px;"
	this.step2.content = "xml:./content/nuclearwinter.xml#step2"; //getCtrlHandle("step2_content").innerHTML;

//https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9389375

	// Donation Complete
	this.donationcomplete = new iView;
	this.donationcomplete.title = "Download "+this.title+" - Donation Complete";
	//this.donationcomplete.content = "<p align=center>Thanks again for your donation and support.</p><p align=center>You will receive an email shortly with a unique URL from which you can download "+title+".  Please contact us if you have any issues";
	this.donationcomplete.content = "xml:./content/nuclearwinter.xml#donationcomplete";
	this.donationcomplete.content = "<p align=center>thanks again for your donation and support.</p><p align=center>please enter the email address you made your donation with to download "+this.title+". <div align=center id=''><input type=text name='donemail' id='donemail'> <input type='button' name=doncomp id=doncomp value=' Start Download ' onclick=\"__postback('startdownload');\"></div>";

	// Download Album
	this.download = new iView;
	this.download.title = "Download "+this.title+" ";
	this.download.content = "xml:./content/nuclearwinter.xml#download";
	//this.download.content = "<p align=center><b>Thank You</b><p align=center>You will receive an email shortly<br>with a unique URL from which you can download "+title+".";
	//this.download.content = "<p align=center><a href='#startdownload' onclick=\"__postback('startdownload');\">Start Download</a>";

}

// -----------------------------------------------------------
// iView code
// -----------------------------------------------------------

function viewControls(ob)
{
	this.parent = ob;
	this.close = "<div style=\"width:15px;float:right;\"><a onclick=\""+this.parent.closeview+"\">X</a></div>";
	//closeView('');
	this.minimize = "";
	this.size = "";
	this.move = "";
}

function iView()
{
	this.title = "";
	this.width = 600;
	this.height = "";
	this.top = "center";
	this.right = "center";
	this.cssclass = "";
	this.content = null;
	this.dcont = null;
	this.onopen = null;
	this.onclose = null;
	this.state = null;
	this.parent = getCtrlHandle("float");
	this.dhndl = null; // once created, stores the controls DOM handle	
	this.controls = new viewControls(this);

	this.activateview = function()
	{
		if (this.dhndl != null)
		{
			// set width, height
			// set position		

			if (this.onopen != null) this.onopen();
			this.parent.style.display = "";
			this.dhndl.style.display = "";
			// need to be fixed..
			if (iViews.activeview != null) iViews.activeview.closeview();
			iViews.activeview = this;
		}
	}
	
	this.closeview = function()
	{
		if (this.dhndl != null)
		{	
			this.dhndl.style.display = "none";
			iViews.activeview = null;
			if (this.onclose != null) this.onclose();
		}
	}
	
	this.loadcontent = function(target)
	{
		target = (target == "undefined") ? this.dhndl : target;
		switch (this.content.substr(0,3))
		{
			case "xml":
				// get guid from content
				target.innerHTML = fetchViewContent(this.content.substr(4).split("#")[0], this.content.substr(this.content.indexOf("#")+1,this.content.length));
				break;
			case "url":
				target.innerHTML = fetchViewContent(this.content.substr(4,this.content.length));
				break;
			default:
				target.innerHTML = this.content;
		}
	}

	//if (typeof(arguments[0].length) != "undefined") this.name = arguments[0];

}

function actionView (vname)
{
	// redirect to hard link if incapable browser
	if (legacy_mode)
	{
		window.location = window.location.pathname + "?step="+vname;
		return false;
	}

	// is view defined?
	//alert(typeof(eval("pageViews."+vname))+"/"+eval("pageViews."+vname).title);
	if (typeof(eval("iViews."+vname)) == "undefined") return alert(vname+" does not exist.");
	var vHndl = eval("iViews."+vname);
	
	// make sure we have a main control
	if (!(peHndl = getCtrlHandle("float"))) return alert("Unable to load view.");
	
	// has the view already been created? create view wnd...
	if (vHndl.dhndl == null || typeof(vHndl.dhndl) != "object")
	{
		vdHndl = createDOMLayer(peHndl, "", "", "class", vname);
		vdHndl.style.display = "none";
		vtHndl = createDOMLayer(vdHndl, "", "", "wtitle", vname+"-title");			
		vcHndl = createDOMLayer(vdHndl, "", "", "wcontent", vname+"-content");
		vHndl.dhndl = vdHndl;
	} else {
		// append vname to 'title' and 'content'
		vtHndl = getCtrlHandle(vname+"-title");
		vcHndl = getCtrlHandle(vname+"-content");
	}
	
	// set title, if defined
	vtHndl.innerHTML = vHndl.title + vHndl.controls.close;
	if (vtHndl.width) vtHndl.style.width = vtHndl.width;

	// doe'et	
	vHndl.loadcontent(vcHndl);

	// FUTURE: tween...
		// run animation to dispaly view (grow from top left)
		// run animation to hide view (shrink to top left)
		
	// execute onload if set
	//if (vHndl.onload != null) vHndl.onload();
	
	vHndl.activateview();
	
	return;
}


function getCtrlHandle() {
	var ctrlName = getCtrlHandle.arguments[0];
	var ctrlHndl;

	// get handle of object
	if (document.all) {  // ie or similar
		var ctrlHndl = eval("document.all."+ctrlName);
	} else {  // other
		if (ctrlName.indexOf(".") > 0) {
			while (ctrlName.indexOf(".") > 0) {
				tcName = ctrlName.substr(0, ctrlName.indexOf("."));
				ctrlHndl = document.getElementById(tcName);
				ctrlName = ctrlName.substr(ctrlName.indexOf(".")+1, ctrlName.length);
			}
			ctrlHndl = eval("ctrlHndl."+ctrlName);
		} else {
			ctrlHndl = document.getElementById(ctrlName);
		}
	}
	
	if (ctrlHndl) {
		return ctrlHndl;
	} else {
		return;
	}
}

// v.6
function fetchViewContent(curl,guid)
{
	thatstuff = simpleSynXMLRequest(curl);
	
	// fd
	if (thatstuff.responseText.length > 0)
	{		
	}
	
	// get content from guid, loop through items until GUID is matched
	if (guid && guid.length > 0)
	{
		content = "";
		rXHndl = thatstuff.responseXML;
			if (!thatstuff.responseXML) {
				var rXHndl = (new DOMParser()).parseFromString(thatstuff.responseText, "text/xml");
			} else {
				var rXHndl = thatstuff.responseXML;  //alert(args[1].responseText);
			}
		fd = rXHndl.getElementsByTagName("item");
		for (x=0;x<fd.length;x++)
		{
			r = rXHndl.getElementsByTagName("item")[x];
			if (getElementTextNS("", "guid", r, 0) == guid) content = getElementTextNS("", "description", r, 0);
		}
	}
	else
	{
		content = thatstuff.responseText;
	}
	
	if (thatstuff.status >= 400)
	{
		return "An error occured while retrieving the requested content.";
	}
	else
	{
		//alert(thatstuff.responseText);
		return content;
	}	
}

/*
	***********************************************

	AJAX Functions

	***********************************************
*/


var htreq;
var isIE = false;

function getXMLRequestHndl() {

	if (window.XMLHttpRequest)
		return http = new XMLHttpRequest();
	else if (window.ActiveXObject)
		return http = new ActiveXObject("Microsoft.XMLHTTP");

}

function simpleXMLRequest() {
	var args = simpleXMLRequest.arguments;
	var reqURL = args[0];
	var metho = args[1];
	var addlFuncArgs = new Array();
	for (x=2;x<=args.length;x++) { addlFuncArgs[x-2] = args[x]; }

	// pre-submit operations
	if (!eval(metho+"('pre',null,'"+addlFuncArgs.join("','")+"')")) return;

	// branch for native XMLHttpRequest object
	var htreq = getXMLRequestHndl();

	if (htreq && args.length > 1) {
		// set request action
		htreq.onreadystatechange = function () {
			if (htreq.parseError && htreq.parseError != 0) {
				alert("Parse Error line " + htreq.parseError.line + ", character " + htreq.parseError.linePos + '\n' + htreq.parseError.srcText);
			}
			// only if req ready
			if (htreq.readyState == 4) {
				// load if "OK"
				if (htreq.status == 200) {
					// do the stuff
					//alert(metho+"('success',htreq,'"+addlFuncArgs.join("','")+"')");
					if (!eval(metho+"('success',htreq,'"+addlFuncArgs.join("','")+"')")) alert(metho+" failed on execution.");
				} else {
					if (!eval(metho+"('error',htreq,'"+addlFuncArgs.join("','")+"')")) {
						alert("There was a problem retrieving the XML data:\n" + htreq.statusText + " (" + htreq.status + ")");
					}
				}
			}
		};

		htreq.open("GET", reqURL, true);
	    //htreq.setRequestHeader("Content-type", "text/xml");
		if (window.ActiveXObject)
			htreq.send();
		else
			htreq.send(null);

	}

	return;
}

// v.2b
function simpleSynXMLRequest() {
	var args = simpleSynXMLRequest.arguments;
	var reqURL = args[0];

	// branch for native XMLHttpRequest object
	var htreq = getXMLRequestHndl();

	if (htreq && args.length >= 1) {

		htreq.open("GET", reqURL, false);
	    //htreq.setRequestHeader("Content-type", "text/xml");

		if (window.ActiveXObject)
			htreq.send();
		else
			htreq.send(null);
			
		// process sync request
		if (htreq.parseError && htreq.parseError != 0) {
			alert("Parse Error line " + htreq.parseError.line + ", character " + htreq.parseError.linePos + '\n' + htreq.parseError.srcText);
		}

		// only if req ready
		if (htreq.readyState == 4) {
			return htreq;
			/*
			if (htreq.status == 200)  // load if "OK"
			{
			} else {
			}
			*/
		}

	}

	return;
}

/*
	***********************************************

	DOM Functions

	***********************************************
*/

function createDOMLayer() {
	var dHndl = createDOMLayer.arguments[0];

	// create the Layer
	var ndHndl = document.createElement('div');
	// set attributes<div 
	ndHndl.innerHTML = createDOMLayer.arguments[1];
	ndHndl.setAttribute("align", createDOMLayer.arguments[2]);
	ndHndl.setAttribute("class", createDOMLayer.arguments[3]);
	ndHndl.setAttribute("id", createDOMLayer.arguments[4]);
	ndHndl.setAttribute("style", createDOMLayer.arguments[5]);
	// append Layer
	dHndl.appendChild(ndHndl);

	return ndHndl;
}

// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method 
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided 
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes 
        if (result.childNodes.length > 1) {
            return (result.childNodes[1] ? result.childNodes[1].nodeValue : "");
        } else {
            return (result.firstChild ? result.firstChild.nodeValue : "");
        }
    } else {
        return "n/a";
    }
}

