// System Tools
var System = {
	message: function(msg){
		alert(msg);
		//new Insertion.Top('outer','<div id="msgContainer"><div id="msg">'+msg+'<div id="msgClose" onclick="javascript:System.closeMessage()">close</div></div></div>');
	},
	closeMessage:function(){
		Element.remove('msgContainer');
	},
	confirm: function(msg){
		return confirm(msg);
	},
	debug: function(msg){
		if( Element.getDimensions('debug').height > 700 ) {
			System.clearDebug();
		}
		// Comment out next line to disable debugging msg
		$('debug').innerHTML = 	$('debug').innerHTML + msg + "<br />";
	},
	clearDebug: function(){
		$('debug').innerHTML = "";
	}
}
/* Mimic A exclusive menu group */
var Menu =  Class.create();
Menu.prototype =  {

	nodes: [],
	opts: {},
	selected:null,
	msg: "yo",
	clickHandlers: {},
	toString: function () { return "Menu Object" } ,
	eventHandler: function(ev) {

		var self = Event.element(ev);
		System.debug("handler called:"+self);
		var _this = this;
		this.nodes.each(function (node){
			if( Element.hasClassName(node,_this.opts.selectClass ) ) {
				System.debug("Removing selectclass from:"+node.id);
				Element.removeClassName(node,_this.opts.selectClass )
			}
		});

		Element.addClassName(self,this.opts.selectClass );

		this.selected = self;

		_this = this;
		// Attempt to call a custom click handler if not then default
		return Try.these(
			function(){ _this.clickHandlers[self.id]() },
			function(){ _this.opts.clickHandler(ev) }
		);
	} ,
	addClickListener: function(id,fn) {
		var _id = typeof(id) == "string" ? id : $(id).id ;
		this.clickHandlers[id] = fn;
	},
	// Handle hover action
	hoverHandler: function(ev) {

		var self = Event.element(ev);
		if ( Element.hasClassName(self,this.opts.hoverClass ) ) {
					Element.removeClassName(self,this.opts.hoverClass)
		} else 	{
					Element.addClassName(self,this.opts.hoverClass)
		}
	},
	initialize: function(conf) {
		// Setup up event objects
		this.events = {
		      mouseOver:  this.hoverHandler.bindAsEventListener(this),
		      mouseOut:  this.hoverHandler.bindAsEventListener(this),
		      mouseClick:  this.eventHandler.bindAsEventListener(this)
    	},
		this.opts = {
			parent:conf.parent,
			child:conf.child,
			hoverClass:conf.hoverClass,
			clickHandler:conf.clickHandler,
			selectClass:conf.selectClass
		}

		this.setup();
	},
	setup: function(){

		// Remove Event Listeners if present
		if(this.nodes){
			var _this = this;
			this.nodes.each( function(node){
				Event.stopObserving(node,'mouseover',_this.events.mouseOver,true);
				Event.stopObserving(node, 'mouseout',_this.events.mouseOut,true);
				Event.stopObserving(node,'click', _this.events.mouseClick,true);
			});
		}
		this.nodes = $A( $(this.opts.parent).getElementsByTagName(this.opts.child) );

		// Preserve scope for handler assignment
		_this = this;
		//System.clearDebug();
		this.nodes.each( function(node)
		{
			//System.debug("init:"+node.innerHTML);
			if( Element.hasClassName(node,_this.opts.selectClass ) ) {
				Element.removeClassName(node,_this.opts.selectClass )
			}
			if ( Element.hasClassName(node,_this.opts.hoverClass ) ) {
				Element.removeClassName(node,_this.opts.hoverClass)
			}

			Event.observe(node, 'mouseover',  _this.events.mouseOver, true);
			Event.observe(node, 'mouseout',  _this.events.mouseOut,true);
			Event.observe(node, 'click',  _this.events.mouseClick,true);

		});
		//Effect.Appear(_this.opts.parent,{duration:.2});
	},
	forceSelect: function(selectMe){
		var me = $(selectMe);
		var _this = this; // Temp scope fix

		this.nodes.each(function(node){
			if(node == me ) {
				Element.addClassName(node,_this.opts.selectClass );
				_this.selected = node;
			} else {
				Element.removeClassName(node,_this.opts.hoverClass);
				Element.removeClassName(node,_this.opts.selectClass);
			}
		});
	},
	forceSelectByIndex: function(id){
		var match = false;
		var _this = this;
		this.nodes.each(function(node){
			if( idSplit(node) == id ) {
				_this.forceSelect(node);
				System.debug("Selecting:"+node.id);
				match = true;
			}
		});
		//if( !match ) { alert("no match for "+id+" in "+_this.opts.parent); };
	},
	deselectAll: function()
	{
		_this = this;
		this.nodes.each(function(node){
			Element.removeClassName(node,_this.opts.hoverClass);
			Element.removeClassName(node,_this.opts.selectClass);
			this.selected = null;
		});
	}
}

/************************
*		Helpers	     *
************************/
// Pass in an array of [selectelement,index] pairs
var Select = {

	setByValue:  function(nodes)
	{

		for( var item in nodes ) {
				var element = $(item);
				//System.debug("Searching:"+element.id+" for :"+nodes[item] );
				var opts = element.options;
				for( var a = 0 ; a < opts.length ; a++ )
				{
					if ( opts[a].value == nodes[item] ){
						//System.debug("!found: "+nodes[item]+" at index: " + a);
						element.selectedIndex = a;
						break;
					}
				}
		}
	}
}

/* Index suffix from a css id : selector(_index)  */
String.prototype.idSplit = function(){
	var id =  this.id.match(/_([^_]+)$/)[1];
	System.debug("found id:"+id+ " in:"+this.id);
	return id;
}
/* JS port of uppercase words  */
String.prototype.ucwords = function(){
	var ucstring = "";
	var temp = $A(this.split(" "));
	temp.each(function(s){
		ucstring += ( s.length > 1 ) ? s.substr(0,1).toUpperCase() + s.substr(1,s.length-1) : s.toUpperCase() ;
	});
	return ucstring;
}
/* Strip Slashes From incoming string */
String.prototype.stripSlashes = function(){
	var str = this;
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

/*
*	Pre load image rollovers and setup rollover events
*	Rollovers images must have the _over suffix
*	Note: Requires prototype obviously
*/

function rollOver(obj)
{
	var nm = obj.src.match(/^(.*?)(_over)?\.(\w+)$/i);
	obj.src = ( nm[2] == "_over" ) ? nm[1] + "." + nm[3] : nm[1] + "_over" + "." + nm[3];
}
var rolloverimages = Array();
function setupRollOver(parent,child)
{
	var nodes = $A( $(parent).getElementsByTagName(child) );
	nodes.each(function(node){
		if( ! node.src.match(/_over/i) ) {
			var n = node.src.match(/^(.*?)\.(\w+)$/i);
			var i = new Image();
			i.src=n[1]+"_over."+n[2];
			rolloverimages.push(i);
			node.onmouseover = node.onmouseout = function(){rollOver(this);	}
		}
	});
}

var PopUp = {

}


/* Shopping */

var Cart = {


	add:function(id){

		var img = $('bottomNavBuyImage').src;

		$('bottomNavBuyImage').src = "/images/loader_bar.gif";

		_q = "action=addtocart&product_id="+id;
    
		var ajax = new Ajax.Request('/ajax/',
				{
						onComplete:function(t){
						 $('bottomNavBuyImage').src = img;
             Element.hide('bottomNavBuy');
             Element.show('bottomNavAdded');
						},
						postBody:_q,
						method:'post',
						evalScripts:true
				});
		//alert("Add item to basket:"+id);
	},
	remove:function(n){
		// Get the update amounts
		_q = "action=removefromcart&id="+n;
		// Show the loadbar
		Element.update('cart-inner','<img src="/images/loader_bar.gif" />');
		// Send the request to update the cart
		var ajax = new Ajax.Updater('cart-inner','/ajax/',
				{
						onComplete:function(t){

						},
						postBody:_q,
						method:'post',
						evalScripts:true
				});
	},
	update:function(){

		// Get the update amounts
		_q = "action=updatecart&"+Form.serialize('cart');
		// Show the loadbar
		Element.update('cart-inner','<img src="/images/loader_bar.gif" />');
		// Send the request to update the cart
		var ajax = new Ajax.Updater('cart-inner','/ajax/',
				{
						onComplete:function(t){

						},
						postBody:_q,
						method:'post',
						evalScripts:true
				});
	}

}
