//init
document.ajaxLoaded = false;
document.TEXTresp = null;
document.currentUser = eatCookie('username');


Ajax.currentLightboxRequests = $H({}); //to hold all lightbox-type requests
Ajax.cacheHash = new Object();
Ajax.cacheDex = new Array(); //to track the assoc object...
Ajax.activeLightboxCount = 0;
Ajax.activeLightboxSaveCount = 0;


var bWait = {
	generic: function(e) {
		if (Ajax.activeLightboxSaveCount > 0)
		{
			var event = e || window.event;
			event.returnValue = 'Your changes are still saving... ('+Ajax.activeLightboxSaveCount+')\nIf you click OK you may lose changes.';
			if (  event.preventDefault )
				event.preventDefault();
			else
				new Event(event).preventDefault();
		}
	}
};


//create responder monitor to count active requests
Ajax.Responders.register({
  onCreate: function(request) {
    if (request.options.furl && request.options.furl.match(/\/(Lightbox|Share|R\?)/) ) {
	if ($('view_exp_link')) //view expanded is synchronous, so need to wait for all saves before viewing expanded
	{
		$('view_exp_link').onclick = "alert('Your lightbox is still updaing.  This link will be re-enabled as soon as it is complete'); return false";
		$('view_exp_link').style.color = '#E1E1E1';
	}

        Ajax.activeLightboxCount++;
	if ( request.options.furl.match(/\/(LightboxSave|ShareSet)/) )
	{	
		if (Ajax.activeLightboxSaveCount == 0) //your first..
			Event.observe(window, 'beforeunload', bWait.generic.bindAsEventListener(bWait));
		Ajax.activeLightboxSaveCount++;
	}

	if( ! request.options.furl.match(/\/(Lightbox(Info|Save)|ShareSet)/) )  
        {
	    Ajax.currentLightboxRequests[request.options.furl] = request; 
	    //then serialize and save...
	    var tstr = $A(Ajax.currentLightboxRequests.keys()).toJSON();
	    bakeCookie('lightbox_queue.'+document.currentUser, tstr, 1);
        }
    }

  },
  onComplete: function(request) {
    if (request.options.furl && request.options.furl.match(/\/(Lightbox|Share|R\?)/) ) {

	if (! request.options.furl.match(/\/(Lightbox(Info|Save)|ShareSet)/) )
    	{	
           delete Ajax.currentLightboxRequests[request.options.furl];
           var tstr = $A(Ajax.currentLightboxRequests.keys()).toJSON();
           bakeCookie('lightbox_queue.'+document.currentUser, tstr, 1);
    	}

        if ( request.options.furl.match(/\/(LightboxSave|ShareSet)/) )
        {
		Ajax.activeLightboxSaveCount--;
		if (Ajax.activeLightboxSaveCount == 0) //your last..
			Event.stopObserving(window, 'beforeunload', bWait.generic.bindAsEventListener(bWait));

	}
        Ajax.activeLightboxCount--;

	if (Ajax.activeLightboxCount == 0)
        	if ($('view_exp_link'))
		{
                	$('view_exp_link').onclick = '';
			$('view_exp_link').style.color = '#666666';
		}

    }
  }
});


//shortcuts;
var $GKW;
var $GID;

//object caching
CacheDecider=Class.create();
CacheDecider.prototype = {
    initialize: function(rng){
        //How long do we want to
        //keep the associated data, in seconds?
        this.secondsToCache=rng;
        this.lastFetched=new Date();

    },
    keepData: function(){
        var now = new Date();
        //Get the difference in seconds between the current time
        //and the lastFetched property value
        var secondsDif = parseInt((now.getTime() - 
        this.lastFetched.getTime()) / 1000);
        //If the prior computed value is less than
        //the specified number of seconds to keep
        //a value cached, then return true
        if (secondsDif < this.secondsToCache)  { return true;}
        //the data in the cache will be refreshed or re-fetched,
        //therefore reset the lastFetched value to the current time
        this.lastFetched=new Date();
        return false;
    },
    theData: null
}

localJSONobj = Class.create();
localJSONobj.prototype = {
	initialize: function (rt) {
		try {
			//this.oJSON = eval('('+ rt +')'); //rObj.responseText
			var tsrt = rt + " ";
			this.oJSON = tsrt.evalJSON();
		} catch (e) { console.log('Parse Error: '+e); }

		if (this.oJSON.error)
			alert(this.oJSON.error);
	
		if (this.oJSON.keywords)
			if (this.oJSON.keywords.keywords)
				if (this.oJSON.keywords.keywords.length == 1)
					this.oJSON.keywords.keywords = this.oJSON.keywords.keywords[0].split(", ");


	},
	//then do a quick check on keywords, in case they come as one string	
	getKeywords: function () { 
		//keywords is nested, so 
		if (this.oJSON.keywords.keywords)
			return this.oJSON.keywords.keywords;
		else 
			return;
	},
	getCartDat: function (attrName,count){
		if ( this.oJSON.item && this.oJSON.item[count])
		{ 
			if (this.oJSON.total == 'undefined') //init count on empty cart
                                this.oJSON.total = 0;


                        if (this.oJSON.item[count][attrName])
                                return this.oJSON.item[count][attrName];
                        else
                                return;
		}
		else if (attrName.match(/total/i))
		{
			return this.oJSON.total;
		}
		else
		{
			return;
		}

	},
	getLbDat: function (attrName,count){
		if ( this.oJSON[attrName] ) //single image data
		{
			return this.oJSON[attrName];
		}
		else
		{
			return '';
		}
	},
	getImgDat: function (attrName,count) {
		if ( this.oJSON.item && this.oJSON.item[count]) // looking for an image in the cart 
		{
			if (this.oJSON.total == 'undefined') //init count on empty cart
				this.oJSON.total = 0;

			if (this.oJSON.item[count].image)
				if (this.oJSON.item[count].image[attrName])
					return this.oJSON.item[count].image[attrName];
				else
					return;
		}
		else if ( this.oJSON[attrName] ) //single image data
		{
			return this.oJSON[attrName];
		}
		else
		{
			return '';
		}
		//filter out other site's cart images if this is a cart object
		if (this.oJSON.total && this.oJSON.antphoto)
		{
			var splArr = new Array;
			var siteTotal = 0;
			for (cti=0;cti<this.oJSON.total;cti++)
			{
				if (this.oJSON.antphoto == this.oJSON.item[cti].S_Photog)
				{
					splArr.push(this.oJSON.item[cti]);
				}
			}
			this.oJSON.total = splArr.length;
			this.oJSON.item = splArr;
		}
	},
	oJSON: null
}


function ajax_HTML (oTarget, url, meth, prams) { //takes a target object, url, and method.. optionally params
	if (! oTarget)
		return;
	if(url.match(/\/bin\/Cart\?op\=/))//set cartflasg.. and add a random pram.  Here's why:  Firefox won't POST this properly
	{										// and IE caches it on a GET
		cartdispcheck = 1;
		if (! url.match(/\&drk\=/))
			url += '&drk='+Math.random(10);
	}
	var myAjax = new Ajax.Updater(
		oTarget,
		url, 
		{
                        //evalScripts: true,
			method: meth,
			parameters: prams,
			onComplete: function (oReq) { cartdispcheck = 0; },  //oTarget.innerHTML = oReq.responseText;
			onFailure: function () { /*alert('communications error');*/ }
		}
	);

}

function ajax_TEXT ( url, meth, prams ) {
	document.TEXTresp = false;
	var myAjax = new Ajax.Request(
		url, 
		{
			method: meth, 
			parameters: prams,
			onComplete: function (oReq) { document.TEXTresp = oReq.responseText; },
			onFailure: function () { /*alert('communications error');*/ }
		}
	);
} 

function ajax_JSON (url, meth, prams, synch) {	//last param is DANGEROUS (force to synchronous call..)
	document.ajaxLoaded = false;

	var cachesize = 32;
	var nocache = 0;

	var curl = url;
	if(url.match(/Cart|Lightbox|Share/))//NOCACHE!  //Here's the thing.  Urls for blah.json should never have args, they are arg-less handlers
	{				//so now the AJAXHandler this talks to will totally toss anything it finds after the '?'
					// so just append it here w/ leading ? if it's a cart item
		if ( ! url.match(/(\&|\?)drk\=/)) // don't re-add prams to call that already has them...
		{
			curl += '?drk='+Math.random(10);
			var apprams = prams;
			if (typeof(prams) == 'object' && prams != null )
				apprams = $H(prams).toQueryString();
	                if (apprams && apprams.toString().length < 500)
			{
				curl += '&'+apprams;
				if (meth.match(/GET/i))
					prams = '';
			}
			else if (prams) //must be above..
				meth = 'POST'; //necessarily
		}
		nocache = 1;
	}
        else if (prams && prams != null)
	{
		if (prams.toString().length < 500) 
		{
			curl += '?'+prams;
			if (meth.match(/GET/i))
				prams = '';
		}
		else if (prams)
			meth = 'POST';
	}

	var cacher = Ajax.cacheHash[curl];

	if (! cacher || ! cacher.theData || ! cacher.keepData() || nocache) //nocache forces load every time..
	{
		if(! nocache)
		{
			cacher = new CacheDecider(60*15); //w/i 15 mins...
			Ajax.cacheHash[curl] = cacher; //put empty cacheob in tree..., if ob has no data just overwrite
			Ajax.cacheDex.push(curl);
			//need to check  length of cache and trim out oldest...
			if (Ajax.cacheDex.length > cachesize)
			{
				var furl = Ajax.cacheDex.shift(); //first item in list popped from dex...
				if(furl)
					delete Ajax.cacheHash[furl];
			}
		}
		var myAjax = new Ajax.Request(
			curl, 
			{
				method: meth,
				parameters: prams, 
				furl: curl,
				asynchronous: (synch ? false : true),  //LightboxSave is special.. we want it logged as a responder, but not wait for callback..
				onComplete: function (oBj) { if(! url.match(/LightboxSave/)) { document.ajaxLoaded = true; mkObj(oBj, curl);  } },
				onFailure: function () { /*alert('communications error');*/ }
			});
	}
	else //have it cached
	{
		document.JSONobj = Ajax.cacheHash[curl].theData;
		document.ajaxLoaded = true;
		//SO KEY: Lastly, fire a requested callback if it exists as a 0 level item in the object
		if ( document.JSONobj.oJSON.callback) //( document.JSONobj.oJSON && document.JSONobj.oJSON.callback  && document.JSONobj.oJSON.callback != null)
			eval( document.JSONobj.oJSON.callback );
	}
	

}

/*
JSONobj prototype: 
	JSONobj.keys -> list of child items
	JSONobj.length -> length of child items list...
	JSONobj
if n is object
	JSONobj.n.keys
	JSONobj.n.length
	JSONobj.n
else
	JSONobj.n
...
.....
recurses to a depth of 32...

cart calls: ipnstock.ipndev.com/AjaxHandlers/CartInfo/open.json

*/
function mkObj (rObj, url) {
	var rt = rObj.responseText;
	document.JSONobj = new localJSONobj(rt);
	//and cache, maybe
	if ( Ajax.cacheHash[url] && ! url.match(/Cart|Lightbox|Share/))
		Ajax.cacheHash[url].theData = document.JSONobj;
	//SO KEY: Lastly, fire a requested callback if it exists as a 0 level item in the object
	if ( document.JSONobj.oJSON.callback )
		eval( document.JSONobj.oJSON.callback );		
}

function bakeCookie(name,value,hours) {
	if (hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function eatCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function tossCookie(name) {
	bakeCookie(name,"",1);
}

//next check if we have any lightbox type requests pending...
if ( document.currentUser )
{
	var ltstr = eatCookie('lightbox_queue.'+document.currentUser);
	if (ltstr)
	{
		var tltstr = ltstr + " ";
		var actions = $A(tltstr.evalJSON());

		if (actions.length)
		{
			var last_action = actions.pop();
			actions.each(function(lurl) {
				ajax_JSON(lurl, 'GET', null);
			});
			tossCookie('lightbox_queue.'+document.currentUser);
			ajax_JSON(last_action+'&callback=lightbox_mod_act(0)', 'GET', null);
		}
	}
}
