var useAlphaHack = false;
if((BrowserDetect.browser == "Explorer")&&(BrowserDetect.version < 7.0)&&(BrowserDetect.version >= 5.5)) {
	useAlphaHack = true;
}


//list of objects with an .id attribute.. keeps track of order (list) can be accessed by id (byId)
var MapList = Class.create({
	CLASSDEF: {
		name: 'MapList'
	},
	
	initialize: function(parentObject) {
		this.byId = {};
		this.list = [];
		this.parentObject = parentObject;
	},
	
	add: function(obj) {
		this.byId[obj.id] = obj
		this.list.push(obj);
		obj.parentObject = this.parentObject;
		return obj;
	},
	
	copy: function(newParentObject) {
		var c = new MapList(newParentObject);
		for(var i=0; i < this.list.size(); i++) {
			c.add(this.list[i].copy());
		}
		return c;
	},
  
  clone: function() {
    var c = new MapList(this.parentObject);
		for(var i=0; i < this.list.size(); i++) {
			c.add(this.list[i]);
		}
		return c;
  },
	
	resort: function() { //this assumes the object has a compare(other) function which returns -1 if it is less than other
		this.list = this.qsort(this.list);
	},
	
	qsort: function(a) {
    if (a.length == 0) return [];

    var left = [];
    var right = [];
    var pivot = a[0];
    for (var i = 1; i < a.length; i++) {
        if (a[i].compare(pivot) < 0)
            left.push(a[i]);
        else
            right.push(a[i]);
    }
    return this.qsort(left).concat(pivot, this.qsort(right));
	},
	
	moveUp: function(id) {
		var idx = this.objectIndex(id);
		if(idx ==0) return false;
		return this.swapPos(idx, idx-1);
	},
	
	moveDown: function(id) {
		var idx = this.objectIndex(id);
		if(idx >= this.list.size() -1) return false;
		return this.swapPos(idx, idx+1);
	},
	
	swapPos: function(idx1, idx2) {
		var o1 = this.list[idx1];
		var o2 = this.list[idx2];
		
		var tmp = o1.pos;
		o1.pos = o2.pos;
		o2.pos = tmp;
		this.list[idx1] = o2;
		this.list[idx2] = o1;
    return true;
	},
	
	objectIndex: function(id) {
		for(var i=0; i < this.list.size(); i++) {
			if(this.list[i].id == id) {
				return i;
			}
		}
		return -1;
	},
	
	remove: function(id) {
		var idx = this.objectIndex(id);
		if(idx != -1) {
      var delObj = this.byId[id];
			this.list.splice(idx,1);
			delete this.byId[id];
      return delObj;
		}
    return null;
	},
	
	replace: function(newObj) {
		var idx = this.objectIndex(newObj.id);
		if(idx != -1) {
			this.list[idx] = newObj;
		} else {
			this.list.push(newObj);
		}
		this.byId[newObj.id] = newObj;
	}

});






//queue to load images
var PriorityQueue = Class.create({
    CLASSDEF: {
        name: 'PriorityQueue'
    },
	
	initialize: function() {
		this.imageQueue = {};
		this.imageQueueKeys = [];
		this.lastAdded = 0;
		this.currentQueue = null;
	},
	
	push: function(key, obj) {
		if(this.imageQueue[key] != null) {
			return;
		}
		this.imageQueue[key] = obj;
		var now = new Date().getTime();
		if((now - this.lastAdded > 100)||(this.currentQueue==null)) {
			//start a new queue..
			log("Starting new queue, time diff=" + (now - this.lastAdded));
			if(this.currentQueue!=null) {
				log("Adding existing queue");
				this.imageQueueKeys.push(this.currentQueue);
			}
			this.currentQueue = [];
		} else {
			log("time diff=" + (now - this.lastAdded));
		}
		this.lastAdded = now;
		this.currentQueue.push(key);
	},
	
	pop: function() {
		var keyFound = false;
		var data = null;
		while(!keyFound) {
			var q = this.getCurrentQueue();
			if(q != null) {
				var key = q.shift();
				var data = this.imageQueue[key];
				if(data != null) {
					this.imageQueue[key] = null;
					return data;
				}
			} else {
				return null;
			}
		}
	},
	
	getCurrentQueue: function() {
		if(this.currentQueue==null) {
			return null;
		}
		while(this.currentQueue.size() == 0) {
			if(this.imageQueueKeys.size() == 0) {
				log("Empty Queue");
				this.currentQueue=null;
				return null;
			}
			log("getting next queue");
			this.currentQueue = this.imageQueueKeys.pop();
		}
		return this.currentQueue;
	},
	
	removeFromImageQueue: function(key) {
		this.imageQueue[key] = null;
	}
});




var imageQueue = new PriorityQueue();
var imageQueueRunningCount = 0;


function queueImageLoading(img, src, w, h, callback) {
	var obj = {"img": img, "src":src, "w":w, "h":h, "callback":callback};
	imageQueue.push(src, obj);
	if(imageQueueRunningCount < 2) {
		imageQueueRunningCount ++;
		processImageQueue();
	}
}

function removeFromImageQueue(src) {
	imageQueue.removeFromImageQueue(src);
}

function processImageQueue() {
	var data = imageQueue.pop();
	if(data == null) {
		log("processImageQueue - Empty");
		imageQueueRunningCount --;
		return;
	}
	log("processImageQueue - loading " + data["src"]);
	backgroundLoadImage(data["src"], function() {
			setTransPng(data["img"], data["src"],data["w"], data["h"]);
			data["callback"]();
			processImageQueue();
	}, null);
}

function resetImageQueue() {
	log("Reset Image Queue");
	imageQueue = new PriorityQueue();
}


function backgroundLoadImage(url, callback, callbackData) {
	var cbimg = null;
	
	var cbimg = document.createElement("IMG");
	cbimg.style.display = "none";
	document.body.appendChild(cbimg);
		
	
	var callbackDone = false;
	
	var handler = function() {
		if(callbackDone) {
			log(cbimg.src + ":callbackDone");
			return;
		}
		log(cbimg.src + ":handle");
		callbackDone = true;
		if(!cbimg.complete) {
			log("Failed to load " + cbimg.src);
		}
		if(useAlphaHack) {
			window.setTimeout(function() {
					callback(callbackData);
					document.body.removeChild(cbimg);
			}, 100);
		} else {
			callback(callbackData);
			document.body.removeChild(cbimg);
		}
		
	};
	
	cbimg.onload = handler;
		
	cbimg.onerror = handler;   
	
	cbimg.onabort = handler;
		
	cbimg.src = url;
	if(BrowserDetect.browser == "Explorer") { //other browsers will call the callback..
		if(cbimg.complete) {
			handler();
		} 
	}
}


function setTransPng(img, src, w, h) {
	if(useAlphaHack) {
		if(w != null) {
			img.style.width = w + "px";
		}
		if(h != null) {
			img.style.height = h + "px";
		}
		if(img.tagName == "IMG") {
			img.src = "/ppr/images/trans.gif";
		} else {
			img.style.fontSize = "1px";
		}
		img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '", sizingMethod="scale")';
	} else {
		img.src = src;
		if(w != null) {
			img.width = w;
		}
		if(h != null) {
			img.height = h;
		}
	}
}


var asyncImagesLoading = new Hash();

function setImageUrl(container, img, url, callback) {
	var cbimg = null;
	var elId = null;
	if(img!= null) {
		log("loading image from " + url, true);
		elId = getElId(img);
		if(asyncImagesLoading[elId] != null) {
			asyncFinish(asyncImagesLoading[elId]);
			asyncImagesLoading[elId] = null;
		}
		cbimg = img; 
	} else {
		var cbimg = document.createElement("IMG");
		cbimg.style.display = "none";
		document.body.appendChild(cbimg);
		log("appended async img");
	}
	var callbackDone = false;
	var asyncKey = null;
	cbimg.onload = function() {
			log("async img loaded: " + cbimg.src + " callbackDone=" + callbackDone + " cbimg.complete=" + cbimg.complete);
			if(callbackDone) {
				return;
			}
			callbackDone = true;
			/*
			if(img!=null) {
				log("si");
				img.src = cbimg.src;
				log("sd");
			}
			*/
			if(callback!=null) {
				callback(cbimg.src);
			}
			asyncFinish(asyncKey);
			if(img==null) {
				document.body.removeChild(cbimg);
			}
		};
		
	cbimg.onerror = function() {
		log("error occured loading img:" + url);
		asyncFinish(asyncKey);
	};   
	
	cbimg.onabort = function() {
		log("abort occured loading img:" + url);
		asyncFinish(asyncKey);
	};
		
	cbimg.src = url;
	if(BrowserDetect.browser == "Explorer") {
		if(cbimg.complete) {
			log("async img complete: " + callbackDone);
			/*
			if(img!=null) {
				img.src = cbimg.src;
			}
			*/
			if(callbackDone) {
				return;
			}
			callbackDone = true;
			if(callback!=null) {
				callback(cbimg.src);
			}
			if(img==null) {
				document.body.removeChild(cbimg);
			}
		} else {
			asyncKey = asyncStart(container);
			
		}
	} else {
		//other browsers call onload properly...
		if(container != null) {
			asyncKey = asyncStart(container);
		}
	}
	if(img!= null) {
		asyncImagesLoading[elId] = asyncKey;
	}
	return asyncKey;
}

function setTransparentImage(container, img, url, callback) {
	var elId = getElId(img);
	if(asyncImagesLoading[elId] != null) {
		asyncFinish(asyncImagesLoading[elId]);
		asyncImagesLoading[elId] = null;
	}
	log("loading transparent image from " + url);
	var k = setImageUrl(container, null, url, function(nUrl) {
		
		if(useAlphaHack) {
			img.style.fontSize = "1px";
			img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + nUrl + '", sizingMethod="scale")';
		} else {
			img.src = nUrl;
		}
		if(callback!=null) {
			callback();
		}
	});
	asyncImagesLoading[elId] = k;
	return k;
}

function setBackgroundImage(container, div, url, callback) {
	var elId = getElId(div);
	if(asyncImagesLoading[elId] != null) {
		asyncFinish(asyncImagesLoading[elId]);
		asyncImagesLoading[elId] = null;
	}
	log("loading background image from " + url);
	var k = setImageUrl(container, null, url, function(nUrl) {
		log("setting background image to " + nUrl);
		div.style.backgroundImage = "url(" + nUrl + ")";
		if(callback!=null) {
			callback();
		}
	});
	asyncImagesLoading[elId] = k;
	return k;
}


var pwUtilsNextId = -10000000;
function getNextId() {
	return pwUtilsNextId--;
}

function getElId(el) {
	if((el.id != null)&&(el.id != "")) {
		return el.id;
	}
	el.id = "tmp_id_" + getNextId();
	return el.id;
}

//TAB MANAGMENT
var pwTabs = {};

function registerAppTab(tabsName, tabId, panelId, options) {
	if(pwTabs[tabsName] == null) {
		pwTabs[tabsName] = {};
	}
	var tabs = pwTabs[tabsName];
	tabs[tabId] = {tab: tabId, originalClass: $(tabId).className, panel: panelId, selected: false, options: options==null ? {} : options};
	
	Event.observe($(tabId), "click", function(event) { appTabClick(tabsName, tabId); });
}

function appTabClick(tabsName, tabId) {
	var tabs = pwTabs[tabsName];
	if(tabs[tabId].selected) {
		return;
	}
	var tab = tabs[tabId];
	if(tab.panel == null) {
		tab.panel = tab.options.callback(tabId, tab.options.callbackData);
	}
	if(tab.options.onClick != null) {
		tab.options.onClick(tab.options.onClickData);
	}
	for(var t in tabs) {
		var tab = tabs[t];
		if(tab.tab == tabId) {
			if(tab.originalClass != null) {
				$(tabId).className = tab.originalClass + " alt";
			} else {
				$(tabId).className = "alt";
			}
			log("selecting panel " + tab.panel );
			$(tab.panel).style.display = "";
			tab.selected = true;
		} else {
			if(tab.selected) {
				$(tab.tab).className = tab.originalClass;
				$(tab.panel).style.display = "none";
				tab.selected = false;
			}
		}
	}
	
}

function removeTab(tabsName, tabId) {
	var tabs = pwTabs[tabsName];
	var wasSelected = tabs[tabId].selected;
	delete tabs[tabId];
	return wasSelected;
}

function clearAppTabs(tabsName) {
	delete pwTabs[tabsName];
}


function addUrlParam(url, param) {
  if(url.indexOf("?") != -1) {
    return  url + "&" + param;
  } else {
    return  url + "?" + param;
  }
}

function addSelectOption(el, caption, val, selectedVal) {
  var opt = document.createElement("OPTION");
  opt.text = caption;
  opt.value = val;
  if(selectedVal == val) {
    opt.selected = true;
  }
  if(BrowserDetect.browser == "Explorer") {
    el.options.add(opt);
  } else {
    el.appendChild(opt);
  }
}


function serializeObject(queryComponents, prefix, o, forFormFields) {
  for(k in o) {
    var i = o[k];
    if(typeof i == 'array') {
      serializeArray(queryComponents, prefix + "[" + k + "]", i, forFormFields);
    } else if(typeof i == 'string' || typeof i == 'number' || typeof i == "boolean") {
      if(forFormFields) {
        queryComponents.push([prefix + "[" + k + "]", i]);
      } else {
        queryComponents.push(encodeURIComponent(prefix + "[" + k + "]") + "=" + encodeURIComponent(i));
      }
    } else if(typeof i == 'undefined') {
      //drop it....
      log("serializeObject:" + k + " is undefined"); 
    } else {
      serializeObject(queryComponents, prefix + "[" + k + "]", i, forFormFields);
    }
  }
  return queryComponents;
}

function serializeArray(queryComponents, prefix, o, forFormFields) {
  for(var idx=0; i < o.length; i++) {
    var i = o[idx];
    if(typeof i == 'array') {
      serializeArray(queryComponents, prefix + "[]", i, forFormFields);
    } else if(typeof i == 'string' || typeof i == 'number' || typeof i == "boolean") {
      if(forFormFields) {
        queryComponents.push([prefix + "[]", i]);
      } else {
        queryComponents.push(encodeURIComponent(prefix + "[]") + "=" + encodeURIComponent(i));
      }
    } else if(typeof i == 'undefined') {
      //drop it....
      log("serializeObject: item" + idx + " is undefined"); 
    } else {
      serializeObject(queryComponents, prefix + "[]", i, forFormFields);
    }
  }
  return queryComponents;
}

function copyObject(o) {
  if(o==null) return null;
  var result = {};
  for(k in o) {
    var i = o[k];
    if(typeof i == 'array') {
      result[k] = copyArray(i);
    } else if(typeof i == 'string' || typeof i == 'number' || typeof i == "boolean") {
      result[k] = i;
    } else if(typeof i == 'undefined') {
      //drop it....
      log("copyObject:" + k + " is undefined"); 
    } else {
      result[k] = copyObject(i);
    }
  }
  return result;
}

function copyArray(o) {
  var result = [];
  for(var idx=0; i < o.length; i++) {
    var i = o[idx];
    if(typeof i == 'array') {
      result.push(copyArray(i));
    } else if(typeof i == 'string' || typeof i == 'number' || typeof i == "boolean") {
      result.push(i);
    } else if(typeof i == 'undefined') {
      //drop it....
      log("copyArray: item" + idx + " is undefined"); 
    } else {
      result.push(copyObject(i));
    }
  }
  return result;
}

//MULTILANG STRING TABLE
var mlStringTable = {};
var debugMissingML = false;

function registerMLString(eng,ml) {
  mlStringTable[eng] = {ml:ml, sub: (ml.indexOf("%s") != -1), msub: ml.indexOf("%1s") != -1};
}

function ml(eng, params) {
  var ml = mlStringTable[eng];
  if(ml == null) {
    var subPos = eng.indexOf("%s");
    if(subPos != -1) {
      eng = subMl(eng, params);
    } else {
      subPos = eng.indexOf("%1s");
      if(subPos != -1) {
        eng = subMlm(eng, params);
      } 
    }
    
    if(debugMissingML) {
      return "[" + eng + "]";
    } else {
      return eng;
    }
  } else {
    if(ml.sub) {
      return subMl(ml.ml, params);
    } else if(ml.msub) {
      return subMlm(ml.ml, params);
    } else {
      return ml.ml;
    }
  }
}

function subMl(text, params) {
  return text.replace("%s", params);
}

function subMlm(text, params) {
  for(var i=0; i < params.length; i++) {
    text = text.replace("%" + (i + 1) + "s", params[i]);
  }
  return text;
}

function updateToolTip(el, newText) {
  var elem = $(el);
  var ttId = elem.getAttribute("tool_tip_element_id");
  if(ttId == null) {
    new Tooltip(el, newText);
    return;
  }
  $(ttId).update('<b>' + newText + '</b>');
}

function processToolTips(container) {
  var ttips= Selector.findChildElements(container, $A([".hasToolTip"]));

  if (ttips  == null || ttips.length == null) return;
	for(var i=0; i < ttips.length; i++) {
	  new Tooltip(ttips[i]);  
	}
}
	
var Tooltip = Class.create();

Tooltip.prototype = {
	initialize: function(el, tip) {
		this.el = $(el);
		this.initialized = false;
		this.elMoved = true;
		var ttId = this.el.getAttribute("tool_tip_element_id");
		var int_tip = null;
		var updatingToolTip = false;
		if(ttId != null) {
		  int_tip = $(ttId);
		  updatingToolTip = true;
		} else {
		  int_tip=document.createElement('b');
		  document.body.appendChild(int_tip);
		  ttId = getElId(int_tip);
		  this.el.setAttribute("tool_tip_element_id",ttId);
		}
		 
		if(tip != null) {
		  if(typeof tip == "string") {
		    int_tip.innerHTML='<b>' + tip + '</b>';
		  } else {
		    int_tip.innerHTML=tip.innerHTML;
		  }
		} else {
		  tipText = el.getAttribute("tooltip");
		  if(tipText != null) {
		    int_tip.innerHTML='<b>' + tipText + '</b>';
		  }
		}
		int_tip.className="tip";

		if(updatingToolTip) {
		   //do nothing so this object can get collected....
		   this.el = null;
		} else {
      this.tooltip=int_tip;
   
      // Event handlers
      this.showEvent = this.show.bindAsEventListener(this);
      this.hideEvent = this.hide.bindAsEventListener(this);
      this.updateEvent = this.update.bindAsEventListener(this);
      this.bodyMoveEvent = this.bodyMove.bindAsEventListener(this);
      Event.observe(this.el, "mouseover", this.showEvent );
      Event.observe(this.el, "mouseout", this.hideEvent );
    }
	},
	
	show: function(e) {
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		if(!this.initialized) this.timeout = window.setTimeout(this.appear.bind(this), 250);
	},
	
	hide: function(e) {
		if(this.initialized) {
			Event.stopObserving(this.el, "mousemove", this.updateEvent);
			Event.stopObserving(document.body, "mousemove", this.bodyMoveEvent);
			this.tooltip.style.display="none";
		}
		this._clearTimeout(this.timeout);
		this.initialized = false;
	},
	
	bodyMove: function(e) {
	  if(this.elMoved) {
	    this.elMoved = false;
	  } else {
	    this.hide(e);
	  }
	},
	
	update: function(e){
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		this.setup();
		this.elMoved = true;
	},
	
	appear: function() {
		Event.observe(this.el, "mousemove", this.updateEvent);
		Event.observe(document.body, "mousemove", this.bodyMoveEvent );
		this.setup();
		
		this.initialized = true;
		this.tooltip.style.display="block";
	},
	
	setup: function(){
		this.tooltip.style.left = this.xCord +20 + "px";
		this.tooltip.style.top = this.yCord + 20 + "px";
	},
		
	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};


var Product_image = Class.create();

Product_image.prototype = {
  initialize: function(row_id, width){
    this.empty_width=width;
    this.row=$(row_id);
    this.row_li=$$("#"+row_id+">li");
	this.base_image=$$("#"+row_id+">li img");
    
	this.row_over=$$("#"+row_id+" .over");
	this.row_corners=$$("#"+row_id+" .corners");
    this.row_details=$$("#"+row_id+">li .details");
    this.details_height=0;
    this.change_height=false;
    
    this.width=this.row_li[0].offsetWidth;
    
    this.base_width=this.row.offsetWidth;
    
    this.per_row=Math.floor(this.base_width/this.width);
    this.per_row=(this.base_width%this.width)==0 ? this.per_row-1 : this.per_row;
    
    this.gaps=this.per_row;
     this.set_gaps();
    
	 if(this.gap_width<5){
      this.per_row=this.per_row-1;
      this.gaps=this.per_row;
      this.set_gaps();
    }
    
    this.set_width();
    this.set_overlay();
	
	for(q=0; q<this.base_image.length; q++){
		if(this.base_image[q].complete){
				this.test_image(q);
		}else{
			Event.observe(this.base_image[q], 'load', this.test_image.bind(this, q));
		}
	}
  },
  
  test_image: function(q){
	  if(this.base_image[q].width!=this.empty_width){
		  var margin=(this.empty_width-this.base_image[q].width)/2;
		  this.row_corners[q].style.width=this.base_image[q].width+"px";
		  this.row_corners[q].style.marginLeft=margin+"px";
		  this.base_image[q].style.marginLeft=margin+"px";
	  }
	  if(this.base_image[q].height!=this.empty_width){
		  var margin=(this.empty_width-this.base_image[q].height)/2;
		  this.row_corners[q].style.height=this.base_image[q].height+"px";
		  this.row_corners[q].style.marginTop=margin+"px";
		  this.base_image[q].style.marginTop=margin+"px";
	  }
  },
  set_width: function(){
    row_left=0;
    if(this.row_li.length%this.per_row!=0){
      row_left=this.per_row-(this.row_li.length%this.per_row);
    }
    
    for(x=0; x<(this.row_li.length+row_left); x++){
      offset=0;
      if(x>=this.row_li.length){
      }else{
        
        if(this.row_details[x].offsetHeight>this.details_height){
          this.details_height=this.row_details[x].offsetHeight;
        }
        if(this.row_details[x].offsetHeight!=this.details_height&&this.details_height!=0){
          this.change_height=true;
        }
        
        int_row=this.row_li[x];
        if(this.row_li[x].offsetWidth>this.width){
          offset=this.row_li[x].offsetWidth-this.width;
        }
      }
	  	int_row.setStyle({
						   "margin-left" : this.gap_left-offset+"px",
						   "margin-right" : this.gap_right-offset+"px"
					   });
	  	//int_row.style.marginLeft=
        //int_row.style.marginRight=this.gap_width-offset+"px";
    }
    if(this.change_height=true) this.set_height();
  }, 
  set_height: function(){
	
    for(y=0; y<this.row_details.length; y++){
		this.row_details[y].style.width=this.row_li[0].offsetWidth+"px";
		this.row_details[y].style.height=this.details_height+"px";
    }
  },
  set_gaps: function(){
    this.difference=(this.base_width-(this.per_row*this.width));
    this.gap_width=Math.floor(this.difference/this.gaps);
	this.gap_left=Math.ceil(this.gap_width/2);
	this.gap_right=Math.floor(this.gap_width/2);
  }, 
  set_overlay: function(){
	  //var over_width=this.base_image.offsetWidth;
	  //var over_offset=this.row_over[0].offsetWidth-this.row_over[0].style.width.replace("px", "");
	  //var over_final=over_width-over_offset;
	  var over_final=this.empty_width;
	  
	  for(x=0; x<this.row_over.length; x++){
		 this.row_over[x].style.width=over_final+"px";
		 this.row_over[x].style.height=over_final+"px";
		 this.row_over[x].style.visibility="visible";
		 
		 this.row_corners[x].style.width=over_final+"px";
		 this.row_corners[x].style.height=over_final+"px";
		 this.row_corners[x].style.visibility="visible";
	  }
  }, 
  
  clean_up: function(){
	  alert('clean clean clean');
  }
}

var Rollover_engine=Class.create();

Rollover_engine.prototype={
  initialize: function(li_a, li_img, height){
    this.li_a=li_a;
    this.li_img=li_img;
    
    this.height=height;
    
    this.showEvent = this.show.bindAsEventListener(this);
    this.hideEvent = this.hide.bindAsEventListener(this);
    
    Event.observe(this.li_a, "mouseover", this.showEvent );
    Event.observe(this.li_a, "mouseout", this.hideEvent );
  }, 
  
  show: function(){
    new Effect.Morph(this.li_img, { style:"margin-top: -"+this.height+"px;", duration: 0.3 });
  },
  
  hide: function(){
    new Effect.Morph(this.li_img, { style:"margin-top: 0;", duration: 0.3 });
  }
}


var Popup = Class.create();

Popup.prototype = {
	initialize: function(el, img) {
		
		this.el=el;
		this.imgurl=img.value;
		this.init=false;
		
		this.showEvent = this.show.bindAsEventListener(this);
		this.hideEvent = this.hide.bindAsEventListener(this);
		this.updateEvent = this.update.bindAsEventListener(this);
		Event.observe(this.el, "mouseover", this.showEvent );
		Event.observe(this.el, "mouseout", this.hideEvent );
		 
	},
	
	show: function(e) {
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		
		if(!this.init){
			this.img=document.createElement('img');
			this.img.src=this.imgurl;
			this.img.className="preview_image";
			document.body.appendChild(this.img);
			this.init=true;
		}
		
		this.timeout = window.setTimeout(this.appear.bind(this), 250);
	},
	
	hide: function(e) {
		Event.stopObserving(this.el, "mousemove", this.updateEvent);
		this.img.style.display="none";
		
		clearTimeout(this.timeout);
		clearInterval(this.timeout);
	},
	
	update: function(e){
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		this.setup();
	},
	
	appear: function() {
		Event.observe(this.el, "mousemove", this.updateEvent);
		this.setup();
		this.img.style.display="block";
	},
	
	setup: function(){
		
		var scroll_x=window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft;
		var scroll_y=window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
		
		var int_x=(this.xCord-scroll_x)+this.img.offsetWidth;
		var int_y=(this.yCord-scroll_y)+this.img.offsetHeight;
		
		var margin_x=(int_x>document.body.clientWidth) ? -(20+this.img.offsetWidth) : 20;
		var margin_y=(int_y>document.body.clientHeight) ? -(20+this.img.offsetHeight) : 20;
		
		this.img.style.left = this.xCord + margin_x + "px";
		this.img.style.top = this.yCord + margin_y + "px";
	},
		
	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};

Event.observe(window, "load", function(){
	var my_prev=$$('input.preview_image');
	if (my_prev.length>0){
		var my_a=$$('a.preview_link');
		
		for(x=0; x<my_a.length; x++){
			new Popup(my_a[x], my_prev[x]);
		}
	}
});

function get_page_pos(elem){
	var x_pos = elem.offsetLeft;
	temp_el = elem.offsetParent;
	try {
		while (temp_el != null) {
			int_x=temp_el.offsetLeft;
			if(int_x) x_pos += temp_el.offsetLeft;
			temp_el = temp_el.offsetParent;
		}
	}
	catch(ex){}
	return x_pos;
	//return 40;
}

function get_page_ypos(elem){
	var y_pos = elem.offsetTop;
	temp_el = elem.offsetParent;
	try {
		while (temp_el != null) {
			int_y=temp_el.offsetTop;
			if(int_y) y_pos += temp_el.offsetTop;
			temp_el = temp_el.offsetParent;
		}
	}
	catch(ex){}
	return y_pos;
	//return 40;
}

var cartDetails = {
  refresh: true,
  cost: 0
};
var slidebox=new Array();
var open_extra=null;
Event.observe(window, "load", function() {
  if(pwUsingExtras == true) {
    var a=document.getElementById('extras');
    var b=a.getElementsByTagName('a');
    var cont=$$('.extra_container');

    for(x=0; x<b.length; x++){
      b[x].onclick=function(){
        var c=$$('#extras li');
        var my_a=$$('#extras li a');
        for(y=0; y<c.length; y++){ 
          c[y].className=c[y].className.replace(" alt", "");
          if(my_a[y]==this){
            this.parentNode.parentNode.className+=" alt";
            if(open_extra!=cont[y].id){
              manage_extras(cont[y].id);
            }else{ close_extras(c[y]); }
          }
        } ;
        if(this.id=="pw_c_popup_link"){
          pwCurSelectCurrency();
        }
        return false;
      };
    }
  }
  test_ul(); //moved to the end of index_portal for testing. (ie. so it works)
});

function manage_extras(element){
  var element=$(element);
  if ( window["load"+element.id] ){ window["load"+element.id](); }
  if(open_extra!=null){
    open_extra=$(open_extra);
    new Effect.SlideUp(open_extra, { transition: Effect.Transitions.easeInOutCubic, duration: 0.5, afterFinish: function() { if(open_extra!=null) { new Effect.SlideDown(element, { transition: Effect.Transitions.easeInOutCubic, duration: 0.5 } ); open_extra=element.id; } } } );
  }else{
    new Effect.SlideDown(element, { transition: Effect.Transitions.easeInOutCubic, duration: 0.5, afterFinish: function(){ open_extra=element.id; } } );
  }
}
function close_extras(my_li){
  new Effect.SlideUp(open_extra, { duration: 0.5,  afterFinish: function() { my_li.className=my_li.className.replace(" alt", ""); open_extra=null; }  } );
}

function loadcart(){
  if (cartDetails.refresh) {
    if($("top_cart_notice") != null) {
      $("top_cart_notice").innerHTML = "<h3 class='loading'>Loading</h3>";
      $("top_cart_notice").show();
    }
    new Ajax.Request("/ppr/shop/cart_info", {
      method: 'get', 
      onSuccess: function(transport, json) { 
        //$("top_cart_notice").hide();
        
        cartDetails.refresh = false;
        if(!json) {json = transport.responseText.evalJSON(); }
        var cart = json.cart;
      
        if($("cart_count") != null) {
          $("cart_count").innerHTML = json.cart.qty ;
          if (parseInt(json.cart.qty,10) != 1){
            $("cart_count").innerHTML = json.cart.qty+" items" ;
          }else{
            $("cart_count").innerHTML = "1 item" ;
          }
        }
        if($('cart_cost') != null) {
          if (parseFloat(json.cart.price) > 0) {
          //$('cart_cost').innerHTML = pwCurFormatAmount(parseFloat(json.cart.price))+ " " + pwCurCur[1];
          pwCurArea(parseFloat(json.cart.price), null, null, true, null, null, null, null, 'cart_cost');
          } else {
          //$('cart_cost').innerHTML = pwCurFormatAmount(0) + " " + pwCurCur[1];
          pwCurArea(0, null, null, true, null, null, null, null, 'cart_cost');
          }
        }
        cartDetails.cost = parseFloat(json.cart.price);
      
        if(($("top_cart_notice") != null)&&($("item_list") != null)&&($("cart_checkout_link")!= null)) {
          if(parseInt(json.cart.qty,10) > 0){
            Effect.Fade($("top_cart_notice"), { duration: 0.2 });
            $("item_list").innerHTML = "";
            $("cart_checkout_link").onclick = function(){  };
            Element.removeClassName("cart_checkout_link", "disabled");
          }else{
            //$("cart_loading_text").innerHTML = "You have no items in your cart.";
              Effect.Fade($("top_cart_notice"), { duration: 0.2, afterFinish: function(){ $("top_cart_notice").innerHTML = "<h3 class='empty'>You have no items in your cart.</h3>"; Effect.Appear($("top_cart_notice"), { duration: 0.2 }); } });
              //$("top_cart_notice").show();
          }
        }
        if($('cart_link') != null) {
          $('cart_link').childElements()[0].innerHTML = "cart: "+json.cart.link_text;
        }
      
        if($("item_list") != null) {
          json.products.each(function(item){
            var li = "<li id='item"+item.id+"' style='display:none'><div><img src='"+item.url+"' width='77px', height='77px'></div></li>";
            new Insertion.Bottom("item_list", li);
            test_ul();
            Effect.Appear("item"+item.id, { duration: 0.2 });
          });
        }
      }
    }) ;
  }else{ // we are just needing to update the cost incase the currency has changed
    if($('cart_cost') != null) {
      if (cartDetails.cost > 0) {
        //$('cart_cost').innerHTML = pwCurFormatAmount(cartDetails.cost)+ " " + pwCurCur[1];
        pwCurArea(cartDetails.cost, null, null, true, null, null, null, null, 'cart_cost');
      } else {
        //$('cart_cost').innerHTML = pwCurFormatAmount(0) + " " + pwCurCur[1];
        pwCurArea(0, null, null, true, null, null, null, null, 'cart_cost');
      }
    }
  }
}

function updateCart() {
  cartDetails.refresh = true;
  loadcart();
}

function createEle(name) { return $(document.createElement(name)); }



function test_ul(element){
  var my_div=document.getElementsByTagName('div');
  for(x=0; x<my_div.length; x++){
    if(my_div[x].className=="slidebox"){
      slidebox[slidebox.length]=new Sliderclass(my_div[x], x);
    }
  }
}

function Sliderclass(element, num){
  var amt=86;
  
  var num=num;
  var base=element;
  
  base.id="base_"+num;
  var bid=base.id;
  
  var my_window=$$('#'+bid+' div.viewer');
  var win_width=my_window[0].style.width;
  win_width=win_width.replace("px", "");
  
  var base_ul=$$('#'+bid+' ul.test_ul');
  base_ul=base_ul[0];
  var base_li=$$('#'+bid+' ul.test_ul li');
  
  var curr_move=false;
  
  var left=$$('#'+bid+' .right');
  left=left[0];
  var right=$$('#'+bid+' .left');
  right=right[0];
  
  var l_on=true;
  var r_on=true;
  
  slider_setup();
  
  function slider_setup(){
    base_ul.style.width=(base_li.length*amt)+"px";
    test_limits(0);
  }
  
  if(!curr_move){
    left.onclick=function(){
      if(l_on){	
        base_margin=(Math.floor((base_ul.style.marginLeft).replace("px", "")/amt))*amt;
        var move_left=(base_ul.style.marginLeft==null)? - amt : base_margin-amt;
        test_limits(move_left);
        move_left=move_left+"px";
        new Effect.Morph(base_ul, { style: 'margin-left:'+move_left, duration: 0.2, afterFinish:function(){ } });
      }
      return false;
    };
    right.onclick=function(){
      if(r_on){
        base_margin=(Math.ceil((base_ul.style.marginLeft).replace("px", "")/amt))*amt;
        var move_right=(base_ul.style.marginLeft==null)? +amt : base_margin+amt;
        test_limits(move_right);
        move_right=move_right+"px";
        new Effect.Morph(base_ul, { style: 'margin-left:'+move_right, duration: 0.2, afterFinish:function(){ } });
      }
      return false;
    };
  }
  function test_limits(end){
    
    var l_curr=l_on;
    var r_curr=r_on;
    
    if(end>=0){ r_on=false; }else{ r_on=true; }
    
    ul_width=parseFloat(base_ul.style.width.replace("px", ""));
    final_bit=eval(ul_width+end-win_width);
    if(final_bit<=0){ l_on=false; }else{ l_on=true; }
    
    if(l_curr!=l_on){
      if(l_on){ 
        new Effect.Morph(left, { style: 'color: #ffffff;', duration: 0.3 });
        //left.style.color="#ffffff";
      }else{
        new Effect.Morph(left, { style: 'color: #404040;', duration: 0.3 });
        //left.style.color="#404040";
      }
    }
    if(r_curr!=r_on){
      if(r_on){
        new Effect.Morph(right, { style: 'color: #ffffff;', duration: 0.3 });
        //right.style.color="#ffffff";
      }else{
        new Effect.Morph(right, { style: 'color: #404040;', duration: 0.3 });
        //right.style.color="#404040";
      }
    }
  }
}

