/*
* wyAjaxObjects, v1.0
*
* all code and designs Copyright 2008 webinicity (http://www.webinicity.com)
* 
* You may not copy, amend or use this code or design without prior 
* agreement from webinicity.
*
*/	
	//*
    //    * AjaxObject is a hypothetical object that encapsulates the transaction
    //    *     request and callback logic for retreiving XML and converting to a Javascript array of values.
    //    *
    //    * handleSuccess( ) provides success case logic
    //    * handleFailure( ) provides failure case logic
    //    * processResult( ) displays the results of the response from both the
    //    * success and failure handlers
    //    * call( ) calling this member starts the transaction request.
    //    */
    var AjaxObject = {

		list: null,
		chunk: null,
		callback: null,
		recordsCount: 0,
		currentChunk: 0,
		setupChunkNum: 0,
		currentRecord: 0,
		chunkSize: 0,
		biteSize: 0,
		triggerPoint: 0, 
		
        handleSuccess:function(o){
	        // This member handles the success response
	        // and passes the response object o to AjaxObject's
	        // processResult member.
            if (AjaxObject.recordsCount > maxRecordLoad) {setSystemMessage("NOTE: restricted to " + maxRecordLoad + " of " + AjaxObject.recordsCount + " records. Zoom in/adjust criteria to see more.", "warning")} // stop loading records and display message that you are not loading them all
            else {setSystemMessage("" + AjaxObject.recordsCount + " properties loaded [found within " + Math.round(proximity) + " miles from map centre]");}
	        this.processResult(o);
        },

        handleFailure:function(o){
	        // Failure handler
	        setSystemMessage("ERROR:  AjaxObject request failed: [" + o.statusText + "] Please refresh page to continue...","error");
        },

        processResult:function(o){
	        // This member is called by handleSuccess
	        //* Please see the Success Case section for more
	        //    * details on the response object's properties.
	        //    * o.tId
	        //    * o.status
	        //    * o.statusText
	        //    * o.getResponseHeader[ ]
	        //    * o.getAllResponseHeaders
	        //    * o.responseText
	        //    * o.responseXML
	        //    * o.argument
	        //    */

			AjaxObject.json = o.responseText;
			if (AjaxObject.json == "" || AjaxObject.recordsCount == 0) { hidePercentLoaded(); return; }; //YAHOO.log("no records found - " + AjaxObject.json + ":" + AjaxObject.recordsCount);
			setTimeout("AjaxObject.setupChunk(AjaxObject.setupChunkNum, AjaxObject.json)",0);
			if (AjaxObject.currentChunk == 0) {
				AjaxObject.currentChunk = 1;					
				// start processing thread for first chunk
				setTimeout("AjaxObject.getValues(" + AjaxObject.currentChunk + ")", 0);
			}
    	    
        },
        
        getChunk:function(chunkNum) {
            //if (AjaxObject.chunk[chunkNum]) return;
			var mgrOptions = { borderPadding: 40, minZoom: 0, maxZoom: 17, trackMarkers: true };
			AjaxObject.chunk[chunkNum] = {visibility: "hide", markerManager: new MarkerManager(map, mgrOptions) };
			AjaxObject.chunk[chunkNum].startRecord = ((AjaxObject.chunkSize * chunkNum)-(AjaxObject.chunkSize)+1);
			AjaxObject.chunk[chunkNum].midRecord = ((AjaxObject.chunkSize * chunkNum)-(AjaxObject.chunkSize)) + AjaxObject.triggerPoint;
			AjaxObject.chunk[chunkNum].endRecord = ((AjaxObject.chunkSize * chunkNum));
            AjaxObject.chunk[chunkNum].loaded = false;
   			var p = AjaxObject.callback.recordsPage;
			p = stringPushValues(p, new Array(AjaxObject.chunk[chunkNum].startRecord, AjaxObject.chunk[chunkNum].endRecord));
			YAHOO.util.Connect.asyncRequest('GET', p, AjaxObject.callback, "");
        },

        setupChunk:function(chunkNum, json) {
            if (AjaxObject.chunk[chunkNum].loaded == true) return;
            AjaxObject.chunk[chunkNum].loaded = true;
			var a;
			eval("a = new Array(" + json + ");");
			//YAHOO.log("a size = " + a.length);
			AjaxObject.list = AjaxObject.list.concat(a);
			//YAHOO.log("list size = " + AjaxObject.list.length);
			if (AjaxObject.chunk[chunkNum].endRecord > AjaxObject.recordsCount) AjaxObject.chunk[chunkNum].endRecord = AjaxObject.recordsCount;
			AjaxObject.setupChunkNum += 1;
        },
                
        getValues:function(chunkNum) {
			//check if chunk has been loaded
            var recLoad = AjaxObject.recordsCount;
            if (recLoad > maxRecordLoad) recLoad = maxRecordLoad;
			if (AjaxObject.list.length < (AjaxObject.chunkSize * chunkNum) && AjaxObject.list.length < recLoad) {
				// wait until it has
				setTimeout("AjaxObject.getValues(" + chunkNum + ")", 10);
			}
			else {
				// process chunk
				var startPoint = AjaxObject.currentRecord + 1;
				var endPoint = AjaxObject.currentRecord + AjaxObject.biteSize;
				if (endPoint > AjaxObject.chunk[chunkNum].endRecord) {
					endPoint = AjaxObject.chunk[chunkNum].endRecord;
				}
				setTimeout("AjaxObject.callback.afterSuccess(" + chunkNum + "," + startPoint + "," + endPoint + ")",10);
				AjaxObject.currentRecord = endPoint;

				if(AjaxObject.currentRecord >= AjaxObject.chunk[chunkNum].midRecord && AjaxObject.chunk[chunkNum].endRecord < recLoad && !AjaxObject.chunk[chunkNum + 1]) {
					// kick off get next chunk
					setTimeout("AjaxObject.getChunk(" + (AjaxObject.currentChunk + 1) + ")", 10);
				}
				if (endPoint < AjaxObject.chunk[chunkNum].endRecord) {
					// not end of this chunk
					setTimeout("AjaxObject.getValues(" + chunkNum + ")", 10);
				}
				else {
					if (endPoint < recLoad) {
						// end of chunk but not end of records
						AjaxObject.currentChunk += 1;
						setTimeout("AjaxObject.getValues(" + AjaxObject.currentChunk + ")", 10);
					}
					else {
					}
				}
			}
        },
        
        getChunkIFromI:function(i) {
			var nodeI = (i % (AjaxObject.chunkSize));
			var chunkNum = Math.floor(i / (AjaxObject.chunkSize)) + 1;
			return { i: nodeI, chunk: chunkNum};
        },
        
        getIFromChunkI:function(chunk, i) {
			return ((chunk-1) * chunkSize) + i;
        },
        
        //*
        //    * call this function with the following params:
        //    *  success:AjaxObject.handleSuccess,
        //    *  failure:AjaxObject.handleFailure,
        //    *  scope: AjaxObject,
        //    *  argument: <page>
        //    *  htmlPage: <page> + ".htm"
        //    */
        startRequest:function(thisCallback) {
	        this.callback = thisCallback;
			AjaxObject.recordsCount = -1;
			
			// get count of new records
			callback =	{ success:HTMLAjaxObject.handleSuccess,
							failure:HTMLAjaxObject.handleFailure,
							variable: "AjaxObject.recordsCount",
							htmlPage: this.callback.countPage
						};
			HTMLAjaxObject.startRequest(callback);
	        
	        if (AjaxObject.chunk) {
       			for (var c = 1; c < AjaxObject.chunk.length; c++) {
					AjaxObject.chunk[c].markerManager.clearMarkers();
				}
				
				AjaxObject.chunk = null;
			}
			
			AjaxObject.chunk = new Array(0);
			AjaxObject.xmlD = null;
			AjaxObject.currentChunk =  0;
			AjaxObject.setupChunkNum = 1;
			AjaxObject.currentRecord = 0;
			AjaxObject.chunkSize = 100;
			AjaxObject.biteSize = 25;
			AjaxObject.triggerPoint = 1;
			
			setTimeout("AjaxObject.cleanAndStart(0)",10);
        },
        
        cleanAndStart:function(start) {
        	if (AjaxObject.list) {
        		var i = start;
        		var end = start + AjaxObject.chunkSize;
        		if (end >= AjaxObject.list.length) end = AjaxObject.list.length;
				for (var i = start; i < end; i++) {
    	            AjaxObject.list[i].marker.remove();
					AjaxObject.list[i] = null;
				}
				if (end == AjaxObject.list.length) {
		    		AjaxObject.list = new Array();
					AjaxObject.getChunk(1);
		    	}
				else setTimeout("AjaxObject.cleanAndStart(" + end + ")",0);		    	
	    	}
	    	else {
	    		AjaxObject.list = new Array();
				AjaxObject.getChunk(1);
	    	}
        }


    };
		

    var HTMLAjaxObject = {
		callback: null,
		
        handleSuccess:function(o){
	        HTMLAjaxObject.processResult(o);
        },

        handleFailure:function(o){
	        // Failure handler
	        setSystemMessage("ERROR:  HTMLAjaxObject request failed: [" + o.statusText + "] Please refresh page to continue...", "error");
        },

        processResult:function(o){
			if (HTMLAjaxObject.callback.div) {
				var html = o.responseText;
				var el1 = new YAHOO.util.Element(HTMLAjaxObject.callback.div);
				el1.set('innerHTML', html);
			}
			else {
				eval(HTMLAjaxObject.callback.variable + " = o.responseText;");
			}
        },
        
        startRequest:function(thisCallback) {
	        this.callback = thisCallback;
			YAHOO.util.Connect.asyncRequest('GET', HTMLAjaxObject.callback.htmlPage, HTMLAjaxObject.callback, "");
        }

    };

    var HTMLAjaxObject2 = {
		callback: null,
		
        handleSuccess:function(o){
	        HTMLAjaxObject2.processResult(o);
        },

        handleFailure:function(o){
	        // Failure handler
	        setSystemMessage("ERROR:  HTMLAjaxObject2 request failed: [" + o.statusText + "] Please refresh page to continue...", "error");
        },

        processResult:function(o){
			if (HTMLAjaxObject2.callback.div) {
				var html = o.responseText;
				var el1 = new YAHOO.util.Element(HTMLAjaxObject2.callback.div);
				el1.set('innerHTML', html);
			}
			else {
				eval(HTMLAjaxObject2.callback.variable + " = o.responseText;");
			}
        },
        
        startRequest:function(thisCallback) {
	        this.callback = thisCallback;
			YAHOO.util.Connect.asyncRequest('GET', HTMLAjaxObject2.callback.htmlPage, HTMLAjaxObject2.callback, "");
        }

    };



	function stringPushValues(str_p, values_p) {
		var occur = str_p.match(/%\d/g);
		var re = null;
		for (var i = 0; i < occur.length; i++) {
		re = new RegExp("%" + (i+1));
		str_p = str_p.replace(re, values_p[i]);
		}
		return str_p;
	}