/* Copyright 2005 Cameron Manderson. All rights reserved. 
 * 
 * No part of this document may be reproduced or copied in any form by any 
 * means without the written permission of Cameron Manderson. Unless 
 * otherwise expressly agreed in writing, the information contained in 
 * this document is subject to change without notice and Cameron Manderson 
 * assumes no responsibility for any alteration to, or any error or other 
 * deficiency, in this document. 
 * 
 * Intellectual property rights in the Document and in all extracts 
 * and things derived from any part of the Document are owned by Cameron 
 * Manderson and will be assigned to Cameron Manderson on their creation.
 * SAJAX technology from is used in this document and does not belong to 
 * Cameron Manderson and is (c) copyright 2005 modernmethod, inc
 * 
 * You will protect all the intellectual property rights relating to the 
 * Document in a manner that is equal to the protection you provide your 
 * own intellectual property. You will notify Cameron Manderson 
 * immediately, and in writing where you become aware of a breach of 
 * Cameron Manderson's intellectual property rights in relation to the 
 * Document. Cameron Manderson may at its sole discretion terminate the 
 * rights granted in this document with immediate effect by notifying you 
 * in writing and you will thereupon return (or destroy and certify that 
 * destruction to Cameron Manderson) all copies and extracts of the 
 * Document in its possession or control. 
 *
 * Cameron Manderson does not indemnify you or any third party in relation 
 * to the content or any use of the content as contemplated in these terms 
 * and conditions. 
 * 
 * This document is governed by the laws of Victoria, Australia and is 
 * intended to be legally binding.
 * 
 * Enquiries regarding the copyright of this file should be directed to
 * Cameron Manderson cam@mink.net.au
 * 
 * Author: Cameron
 * Date: 21/10/2005
 */

var createStateVariables = new Object;

var initialisedVariables = new Object;
initialisedVariables["productCatalogProductCategory"] = false;
initialisedVariables["productCatalogProductBrand"] = false;
initialisedVariables["productCatalogProductDesigner"] = false;

var firstRun = true;
/*
 * AJAX Methods (Sajax Integration)
 * Integration 
 * TODO: If connection not available, don't keep updating the values
 * @author Cameron Manderson 
 */
function getItemRecords(trigger) {
	var connectionAvailable = sajax_init_object();
	if(!connectionAvailable) {		
		var responsePacket = "<wddxPacket version='1.0'><header/><data><struct><var name='values'><struct><var name='productCatalogProductCategory'><struct><var name='13'><string>Seating - Visitor</string></var><var name='23'><string>Seating - Arm / Lounge chairs</string></var><var name='46'><string>Tables - Coffee/Side</string></var><var name='59'><string>Seating - Lounges</string></var><var name='61'><string>Seating - Ottomans/Benches</string></var><var name='80'><string>Tables - Dining</string></var><var name='147'><string>Storage - Residential</string></var><var name='191'><string>Seating - Home</string></var><var name='294'><string>Seating - Corner Lounges</string></var></struct></var><var name='productCatalogProductBrand'><struct><var name='2'><string>Bernabeifreeman</string></var><var name='185'><string>Norman and Quaine</string></var><var name='284'><string>Woodmark</string></var></struct></var><var name='productCatalogProductDesigner'><struct><var name='3'><string>Bernabeifreeman</string></var><var name='186'><string>Norman and Quaine</string></var><var name='285'><string>Charles Wilson</string></var><var name='296'><string>Matt Sheargold</string></var><var name='4031'><string>Jon Goulder</string></var></struct></var></struct></var></struct></data></wddxPacket>";
		var theDeserializer = new WddxDeserializer;
		theDeserializer.preserveVarCase = true;
		var responseObject = theDeserializer.deserialize(responsePacket);
		for(var i in responseObject.values) {
			addOptions(responseObject.values[i], MM_findObj(i));		
		}
	} else { 
		// Locate all the objects
		var fields = new Object;
		var theSerializer = new WddxSerializer;
		theSerializer.preserveVarCase = true;
		var selectionStruct = new Object;		
		if(firstRun == true) { 
			selectionStruct = createStateVariables;
			firstRun = false;
		} else {
			fields["productCatalogProductCategory"] = MM_findObj("productCatalogProductCategory");
			fields["productCatalogProductBrand"] = MM_findObj("productCatalogProductBrand");
			fields["productCatalogProductDesigner"] = MM_findObj("productCatalogProductDesigner");
			//fields["productCatalogProductApplication"] = MM_findObj("productCatalogProductApplication");		
		
			// Collate all the selections
			
			for(var i in fields) {
				if(fields[i] !== null) {
					selectionStruct[i] = (fields[i].selectedIndex > -1) ? fields[i].options[fields[i].selectedIndex].value : null;
				}
			}	
		}
		var structPacket = theSerializer.serialize(selectionStruct);
	    
	    
		// Invoke Server
		x_getItemRecords(trigger, structPacket, getItemRecordsResponse);
	}
}

function getItemRecordsResponse(responsePacket) {		
	// Populate the record fields based on the packet response from the server
	var theDeserializer = new WddxDeserializer;
	theDeserializer.preserveVarCase = true;
	var responseObject = theDeserializer.deserialize(responsePacket);
	if(responseObject !== null) {
		for(var i in responseObject.values) {
			addOptions(responseObject.values[i], MM_findObj(i));		
		}	
	}
//	alert(responseObject.cacheInfo);
//	MM_findObj('debugStr').value = responseObject.cacheInfo + "\n";
//	MM_findObj('debugStr').value += responseObject.debug;
}


function addOptions(object, target) {	
	if(target == null) return;
	if(target.selectedIndex > 0) {
		currentSelectionValue = target.options[target.selectedIndex].value;
	} else {		
		if(createStateVariables[target.name] !== undefined && createStateVariables[target.name] !== null) {
			if(initialisedVariables[target.name] == false) {
				currentSelectionValue = createStateVariables[target.name];
				initialisedVariables[target.name] = true;
			}	
		} else {
			currentSelectionValue = 0;	
		}
	}
	target.options.length = 0;
	var x = 0;
	var y = -1;
	var newOption = document.createElement('option');
	newOption.value = 0;
	newOption.text = 'Any';
	if(newOption.value == currentSelectionValue) 
	  	y = x;	
	 
	target.options[x] = newOption;
	
	// Place in sorting
	var optionsArray = new Array();
	function availableOption(optionValue, optionText) {
		this.optionValue = optionValue;
		this.optionText = optionText;	
	}
	z = 0;
	for(var i in object) {
		optionsArray[z++] = new availableOption(i, object[i]);	
	}	
	// Sort the options (case insensitive bubblesort)
	optionsArray.sort(sortOption);
		for(var x = 0; x < optionsArray.length; x++) {
		var newOption = document.createElement('option');
		newOption.value = optionsArray[x].optionValue;
		newOption.text = optionsArray[x].optionText;
		if(newOption.value == currentSelectionValue)
			y = x + 1;
		target.options[x + 1] = newOption; // standards compliant; doesn't work in IE
	}
	if(y == -1) y = 0;
	target.selectedIndex = y;
}

function sortOption(a, b) { 
	if(a == null) return true;
	if(b == null) return false;
	var x = a.optionText.toLowerCase();
    var y = b.optionText.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

/**
 * Initialises the form based off the elements passed into this script
 */
function initialiseForm() {
	alert("inititalised called");
	var connectionAvailable = sajax_init_object();
	if(!connectionAvailable) {	
		getItemRecords();
	} else {
		// Collate all the selections
		var theSerializer = new WddxSerializer;
		theSerializer.preserveVarCase = true;
		var selectionStruct = createStateVariables;
		var structPacket = theSerializer.serialize(selectionStruct);
		
		// Invoke Server		
		//alert(structPacket);
		x_getItemRecords("productCatalogProductCategory", structPacket, getItemRecordsResponse);
	}
}

//initialiseForm();
/*
 * SAJAX BELOW LINE
 */
		
// remote scripting library
// (c) copyright 2005 modernmethod, inc
var sajax_debug_mode = false;
var sajax_request_type = "POST";

function sajax_debug(text) {
	if (sajax_debug_mode)
		alert("RSD: " + text)
}
function sajax_init_object() {
	sajax_debug("sajax_init_object() called..")
	
	var A;
	try {
		A=new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			A=new ActiveXObject("Microsoft.XMLHTTP");
		} catch (oc) {
			A=null;
		}
	}
	if(!A && typeof XMLHttpRequest != "undefined")
		A = new XMLHttpRequest();
	if (!A)
		sajax_debug("Could not create connection object.");
	return A;
}
function sajax_do_call(func_name, args) {
	var i, x, n;
	var uri;
	var post_data;
	
	uri = "/catalog/engine/searchEngineJS.php?";
	if (sajax_request_type == "GET") {
		if (uri.indexOf("?") == -1) 
			uri = uri + "?rs=" + escape(func_name);
		else
			uri = uri + "&rs=" + escape(func_name);
		for (i = 0; i < args.length-1; i++) 
			uri = uri + "&rsargs[]=" + escape(args[i]);
		uri = uri + "&rsrnd=" + new Date().getTime();
		post_data = null;
	} else {
		post_data = "rs=" + escape(func_name);
		for (i = 0; i < args.length-1; i++) 
			post_data = post_data + "&rsargs[]=" + escape(args[i]);
	}
	
	x = sajax_init_object();
	x.open(sajax_request_type, uri, true);
	if (sajax_request_type == "POST") {
		x.setRequestHeader("Method", "POST " + uri + " HTTP/1.1");
		x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	}
	x.onreadystatechange = function() {
		if (x.readyState != 4) 
			return;
		sajax_debug("received " + x.responseText);
		
		var status;
		var data;
		status = x.responseText.charAt(0);
		data = x.responseText.substring(2);
		if (status == "-") 
			alert("Error: " + data);
		else  
			args[args.length-1](data);
	}
	x.send(post_data);
	sajax_debug(func_name + " uri = " + uri + "/post = " + post_data);
	sajax_debug(func_name + " waiting..");
	delete x;
}
		
				
// wrapper for getItemRecords
function x_getItemRecords() {
	sajax_do_call("getItemRecords",
		x_getItemRecords.arguments);
}
		
		