//JavaScript/ECMAScript routines used by Cult Pens PenFinder, an AJAX
//pen, pencil and accessory finder.
//
//Some functions are modified versions of functions found elsewhere,
//commented as such at the beginning of the functions.  This file is
//copyright to The SQL Workshop Limited.
//
//Methods for making the URLs bookmarkable and 'mailable' are from
// http://ajaxpatterns.org/Unique_URLs
//The basic AJAX routines were initially from
// http://www.harrymaugans.com/2007/03/18/tutorial-ajax-made-easy/

//General tasks that need doing...

//TODO: Check code that reads the hash of the URL - make sure nothing
//could be put there to do anything unfortunate.

//Create HTTP Objects to use for the AJAX communications later.
httpTable = getHTTPObject();
httpTagDescription = getHTTPObject();

var lastHash = "";

addEvent(window, 'load', startup);

function addEvent(obj, evType, fn){
    if (obj.addEventListener){
	obj.addEventListener(evType, fn, false);
	return true;
    } else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
    } else {
	return false;
    }
}

function startup(){
    setInterval(autoUpdate, 1000);
    document.getElementById('optionspan').style.visibility = "hidden";
    displayExtendedHelp('intro');
    //alert(document.inputForm.order.value);
}

function switchBox(){
    //TODO: If any tags in the box we're activating is already in the
    //activeTags box, we should probably delete it from here so users
    //can't add it twice.
    //We have to set the select box by its parent element, rather than
    //just changing the options, to work around a bug in IE.
    document.getElementById('availableTagsContainer').innerHTML = boxes[document.getElementById('boxCats').value];
    displayCategoryHelp(document.getElementById('boxCats').value);
}

function autoUpdate(){
    //This function is run on a timer, doing any work that needs to be
    //kept up to date all the time.
    if (window.location.hash != lastHash) {
	//URL has changed, update the UI accordingly.
	lastHash = window.location.hash;
	updateTagsFromUrl();
	updateTagDescription();
	updateTable();
	updateOptions();
    }
}

function moveTags(box1,box2){
    //Code modified from example at http://www.johnwbartlett.com/CF_tipsNtricks/index.cfm?TopicID=86
    var selID='';
    var selText='';
    for (i=box1.options.length - 1; i>=0; i--){
	if (box1.options[i].selected == true){
	    selID=box1.options[i].value;
	    selText=box1.options[i].text;
	    if(box2.id != "availableTags") {
		var newRow = new Option(selText.replace(/^\s\s\s\s/g, ''),selID);
		box2.options[box2.length]=newRow;
	    }
	    box1.options[i]=null;
	}
    }
    updateURL();
}

function quickTagHelp(){
    //Code modified from example at http://www.johnwbartlett.com/CF_tipsNtricks/index.cfm?TopicID=86
    var selID='';
    var selText='';
    for (i=document.getElementById('availableTags').options.length - 1; i>=0; i--){
	if (document.getElementById('availableTags').options[i].selected == true){
	    displayCategoryHelp(document.getElementById('availableTags').options[i].value);
	}
    }
}

function getActiveTags(){
    //This gets the selected tags (and options) from the list box.
    var tagList = '';
    for (i=document.inputForm.activeTags.options.length - 1; i>=0; i--){
	tagList = document.inputForm.activeTags.options[i].value + ',' + tagList
    }
    if (tagList.length >1){
	tagList = tagList.substring(0, tagList.length - 1);
    }
    //Get any options...
    //if(document.getElementById("showrefillsbox").checked) {
	//if (tagList.length > 1){
	    //tagList = tagList + ",showrefills";
	//}
    //}
    if(document.inputForm.order.value != 'title') {
	if(document.inputForm.order.value == 'priceasc'){
	    tagList = tagList + ",orderpa";
	} else {
	    tagList = tagList + ",orderpd";
	}
    }
    //alert(document.getElementById('optionspan').style.visibility);
    if(document.getElementById('optionspan').style.visibility == "visible"){
	if(document.getElementById('optionbox').checked) {
	    tagList = tagList + ",option";
	}
    }
    return tagList;
}

function getLastTag(){
    var tag = document.inputForm.activeTags.options[document.inputForm.activeTags.options.length - 1].value;
    return tag;
}

function updateURL(){
    //TODO: Get rid of the hard-coded filename.
    if (document.inputForm.activeTags.options.length == 0){
	window.location.href = 'PenFinder.php';
    } else {
	window.location.hash = getActiveTags();
    }
}

function updateTagsFromUrl(){
    //Need to store the passed options somewhere (tick boxes?), and
    //make sure they get picked up again for generating the table.
    var tagList = window.location.hash.replace(/^#/g, '');
    //Check for options...
    //if((','+tagList.toString()+',').indexOf(',showrefills,')!=-1){
	//document.getElementById('showrefillsbox').checked = true;
    //} else {
	//document.getElementById('showrefillsbox').checked = false;
    //}
    //Check for order...
    if((','+tagList.toString()+',').indexOf(',orderpa,')!=-1){
	document.inputForm.order.value = 'priceasc';
    } else if((','+tagList.toString()+',').indexOf(',orderpd,')!=-1) {
	document.inputForm.order.value = 'pricedesc';
    } else {
	document.inputForm.order.value = 'title';
    }
    //Check for refill options...
    var optionTextRefillable = '<input type="checkbox" name="optionbox" id="optionbox" onClick="updateURL();" />Refillable <em>In</em> Chosen Colour(s)? <a href="javascript:displayExtendedHelp(\'rfincol\')">[?]</a>';
    var optionTextColour =  '<input type="checkbox" name="optionbox" id="optionbox" onClick="updateURL();" />Refillable <em>To</em> Chosen Colour(s)? <a href="javascript:displayExtendedHelp(\'rftocol\')">[?]</a>';
    if((','+tagList.toString()+',').indexOf(',refillable,')!=-1){
	//Refillable selected...
	if(containsColours(tagList)) {
	    document.getElementById('optionspan').innerHTML = optionTextRefillable;
	    document.getElementById('optionspan').style.visibility = "visible";
	    if((','+tagList.toString()+',').indexOf(',option,')!=-1){
		document.getElementById('optionbox').checked = true;
	    }
	} else {
	    document.getElementById('optionspan').style.visibility = "hidden";
	}
    } else {
	//Refillable not requested, so depends if colours selected...
	if(containsColours(tagList)) {
	    document.getElementById('optionspan').innerHTML = optionTextColour;
	    document.getElementById('optionspan').style.visibility = "visible";
	    if((','+tagList.toString()+',').indexOf(',option,')!=-1){
		document.getElementById('optionbox').checked = true;
	    }
	} else {
	    document.getElementById('optionspan').style.visibility = "hidden";
	}
    }
    //Remove any non-tags - used for storing options...
    //TODO: These should probably be inside the if statements above.
    tagList = removeFromList(tagList, 'showrefills');
    tagList = removeFromList(tagList, 'orderpa');
    tagList = removeFromList(tagList, 'orderpd');
    tagList = removeFromList(tagList, 'option');
    //Clear the active tags list...
    document.inputForm.activeTags.innerHTML = '';
    //Make an array of the tags from the hash of the URL...
    if (tagList.length > 0){
	var tagsPassed = tagList.split(",");
	//For every entry in that array, end to beginning...
	for (i=0; i<tagsPassed.length; i++){
	    var newTagEntry = new Option(tagsToNames[tagsPassed[i]],tagsPassed[i]);
	    document.inputForm.activeTags.options[document.inputForm.activeTags.length] = newTagEntry;
	}
    }
}

function updateTable(){
    //Allowing for the 'Show Refills' option...
    //If tags don't include any refill tags, and there's no 'showrefills'
    //tag, carry on.  Otherwise, append the 'rhide=1' option.  Strip out
    //the 'showrefills' tag if it is there, before passing on.
    var activeTagsList = getActiveTags();
    document.getElementById('pfresults').innerHTML = "<p>Updating...</p>";
    if((','+activeTagsList.toString()+',').indexOf(',showrefills,')!=-1){
	var showRefills = true;
	activeTagsList = removeFromList(activeTagsList, 'showrefills');
    } else {
	var showRefills = false;
    }
    var endOfUrl = "";
    if(containsRefills(activeTagsList)) {
	//alert('Found Refills!');
	var endOfUrl = "";
    } else {
	if(showRefills){
	    var endOfUrl = "";
	} else {
	    var endOfUrl = "&rhide=1";
	}
    }
    //Allowing for the Order options...
    if((','+activeTagsList.toString()+',').indexOf(',orderpa,')!=-1){
	activeTagsList = removeFromList(activeTagsList, 'orderpa');
	endOfUrl = endOfUrl + "&order=priceasc";
    } else if ((','+activeTagsList.toString()+',').indexOf(',orderpd,')!=-1) {
	activeTagsList = removeFromList(activeTagsList, 'orderpd');
	endOfUrl = endOfUrl + "&order=pricedesc";
    }
    //Allowing for refill options...
    if((','+activeTagsList.toString()+',').indexOf(',option,')!=-1){
	endOfUrl = endOfUrl + "&option=1";
	activeTagsList = removeFromList(activeTagsList, 'option');
    }
    var url = "pf-backend.php?action=getresults&tags=" + activeTagsList + endOfUrl;
    //Make the AJAX request...
    if(callInProgress(httpTable)){
	httpTable.abort();
    }
    //alert(url);
    httpTable.open("GET", url, true);
    httpTable.onreadystatechange = handleHttpResponseTable;
    httpTable.send(" ");
}

function removeFromList(list, toRemove){
    var listArray = list.split(",");
    listArray.remove(toRemove);
    return(listArray.join(","));
}

Array.prototype.remove=function(s){
    for(i=0;i<this.length;i++){
	if(s==this[i]) this.splice(i, 1);
    }
}

function containsRefills(tagList){
    var tagArray = tagList.split(",");
    var foundRefill = false;
    for (i=0; i<tagArray.length; i++){
	if((','+refillTags.toString()+',').indexOf(','+tagArray[i]+',')!=-1){
	    foundRefill = true;
	}
    }
    return(foundRefill);
}

function containsColours(tagList){
    var tagArray = tagList.split(",");
    var foundColour = false;
    for (i=0; i<tagArray.length; i++){
	if((','+colourTags.toString()+',').indexOf(','+tagArray[i]+',')!=-1){
	    foundColour = true;
	}
    }
    return(foundColour);
}

function updateTagDescription(){
    //TODO: Make this check if the activeTags list has an option selected.
    //If so, show the description for the selected tag, not the last one.
    //Once that's done, need to get this to run whenever a tag is
    //selected in that list.
    //document.getElementById('tagDescription').innerHTML = "<p>Updating...</p>";
    if(document.inputForm.activeTags.options.length > 0) {
	var url = "pf-backend.php?action=gettagdescription&tag=" + getLastTag();
	if(callInProgress(httpTagDescription)){
	    httpTable.abort();
	}
	httpTagDescription.open("GET", url, true);
	httpTagDescription.onreadystatechange = handleHttpResponseTD;
	httpTagDescription.send(" ");
    }
}

function displayCategoryHelp(category){
    //document.getElementById('tagDescription').innerHTML = "<p>Updating...</p>";
    var url = "pf-backend.php?action=gettagdescription&tag=" + category;
    if(callInProgress(httpTagDescription)){
	httpTagDescription.abort();
    }
    httpTagDescription.open("GET", url, true);
    httpTagDescription.onreadystatechange = handleHttpResponseTD;
    httpTagDescription.send(" ");
}

function displayExtendedHelp(helpTag){
    //Use the main table area to display a help file as requested.
    if(helpTag == "x") {
	updateTable();
    } else {
	document.getElementById('pfresults').innerHTML = "<p>Updating...</p>";
	var url = "pf-backend.php?action=gettagdescription&tag=xh" + helpTag;
	if(callInProgress(httpTable)){
	    httpTable.abort();
	}
	httpTable.open("GET", url, true);
	httpTable.onreadystatechange = handleHttpResponseHelp;
	httpTable.send(" ");
    }
}

function updateOptions(){
    //Show Refills...
    //if((','+getActiveTags().toString()+',').indexOf(',showrefills,')!=-1){
	//document.getElementById('showrefillsbox').checked = true;
    //} else {
	//document.getElementById('showrefillsbox').checked = false;
    //}
    //Order...
    if((','+getActiveTags().toString()+',').indexOf(',orderpa,')!=-1){
	document.inputForm.order.value = 'priceasc';
    } else if((','+getActiveTags().toString()+',').indexOf(',orderpd,')!=-1) {
	document.inputForm.order.value = 'pricedesc';
    }
}

function getHTTPObject(){
    var xmlhttp;
    
    /*@cc_on
 
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
      try{
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }catch(E){
      xmlhttp = false;
    }
  }
  @else
    xmlhttp = false;
  @end @*/
    
    if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
	try {
	    xmlhttp = new XMLHttpRequest();
	}catch(e){
	    xmlhttp = false;
	}
    }
    
    return xmlhttp;
}

function callInProgress(xmlhttp) {
    //Checking if the passed call is still alive.
    //Code from http://ajaxblog.com/archives/2005/06/01/async-requests-over-an-unreliable-network
    switch ( xmlhttp.readyState ) {
    case 1: case 2: case 3:
	return true;
	break;
	// Case 4 and 0
    default:
	return false;
	break;
    }
}

function handleHttpResponseTable(){
    if(httpTable.readyState == 4){
	document.getElementById('pfresults').innerHTML = httpTable.responseText;
    }
}
function handleHttpResponseTD(){
    if(httpTagDescription.readyState == 4){
	document.getElementById('tagDescription').innerHTML = httpTagDescription.responseText;
    }
}
function handleHttpResponseHelp(){
    if(httpTable.readyState == 4){
	document.getElementById('pfresults').innerHTML = '<div style="background-color: #ccf;"><p><a href="javascript:displayExtendedHelp(\'x\')">[Remove This Help]</a></p>' + httpTable.responseText + "</div>";
    }
}
