/*!
 *
 * Copyright (c) 2008 UberPrints, Inc.
 *
 * Portions of this code Copyright (c) 2007 Cody Lindley:
 *     Thickbox 3.1 - One Box To Rule Them All.
 *     By Cody Lindley (http://www.codylindley.com)
 *     Copyright (c) 2007 cody lindley
 *     Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 */

// global vars
var global_previewWidth = 720;
var global_previewHeight = 420;
var iGlobalProductCount;

$(document).ready(
	initPreviewWin
);

function initPreviewWin(){
	$("a.productPreview").click(function(event){
		
		event.preventDefault();
		this.blur();
		
		showPreview(this.href, this );
	});
	
	$("div.productPreview").click(function(event){
		
		event.preventDefault();
		this.blur();
		
		showPreview(this.title, this );
	});
}


// called when the user clicks on a productPreview link
function showPreview(url, caller) {

	var pid = url.match(/\w+(?=\/?$)/);  // Match the last word before that last '/' or end of string

	/*
	if( url.substring(url.length-1,url.length) == '/' ) {
		url = url.substring(0,url.length-1);
	}
	var pid = url.match(/\w+$/);
	*/
	//var queryString = url.match(/\?(.+)/)[1];
	//var params = parseQueryString( queryString );
	//var pid = params["id"];
	
	//  div layer id's are: [txt/img][product id]__[global product count]
	//    e.g.,  txtGIG200__2 or imgAA20010__12
	var iIndex = caller.id.indexOf('__');
	var iProductCountIndex = iIndex + 2;
	var product_count = caller.id.substring( iProductCountIndex, caller.id.length );
	
	url = '/catalog/product/view.asp?id='+pid;

	if( $("#previewWin").css("display") == "block" ) {
		return refreshProduct(pid);
	}

	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		$("body","html").css({height: "100%", width: "100%"});
		$("html").css("overflow","hidden");
		if (document.getElementById("UP_HideSelect") === null) {//iframe to hide select elements in ie6
			$("body").append("<iframe id='UP_HideSelect'></iframe><div id='pageOverlay'></div><div id='previewWin'></div>");
			$("#pageOverlay").click(TB_remove);
		}
	}else{//all others
		if(document.getElementById("pageOverlay") === null){
			$("body").append("<div id='pageOverlay'></div><div id='previewWin'></div>");
			$("#pageOverlay").click(TB_remove);
		}
	}
	
	$('#previewWin').css("width",global_previewWidth+"px");
	$('#previewWin').css("height",global_previewHeight+"px");

	if(tb_detectMacXFF()){
		$("#pageOverlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
	}else{
		$("#pageOverlay").addClass("TB_overlayBG");//use background and opacity
	}
		
	if ( $('#UP_load').attr("id") ) {
		// do nothing for now
	} else {
		$("body").append("<div id='UP_load' align='center'><img src='/images/global/preload/load-med-bl.gif' /><br/>Loading...</div>");//add loader to the page
	}

	var 	ajaxContentW = global_previewWidth - 30,
		ajaxContentH = global_previewHeight - 50;  // minus the left + right padding

	if (!document.getElementById('PP_ajaxContent')) {  // create only once
		$("#previewWin").append("<div id='PP_title' style='height:20px'><div id='closeWin-div'><a href='#' id='PP_closeWindowButton'>x close window</a></div></div><div id='product_overlay' style='display:none;'></div><div id='PP_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div><div id='PP_footer' style='height:20px'><div id='PP_footerPrevious'><a href='#' id='PP_previousButton'>&laquo;&nbsp;Previous Product</a></div><div id='PP_footerNext'><a href='#' id='PP_nextButton'>Next Product&nbsp;&raquo;</a></div></div>");
		$("#PP_ajaxContent").height(ajaxContentH);
	} else {
		$("#PP_ajaxContent").attr("innerHTML",'');
	}
			
	$("#PP_closeWindowButton").attr("innerHTML","x close window"); // set this in case content was changed by size chart
	$("#PP_closeWindowButton").css("color","");
	$("#PP_closeWindowButton").click( function() { TB_remove(); return false; } );
	$("#PP_previousButton").click( function() { nextProduct(-1); return false; } );
	$("#PP_previousButton").bind("focus",function() {this.blur();return false; });
	$("#PP_nextButton").click( function() { nextProduct(1); return false; } );
	$("#PP_nextButton").bind("focus",function() {this.blur();return false; }); 	
	
	TB_position();
	$("#previewWin").css({display:"block"});
	$('#UP_load').show()	
	loadProduct(pid,url,function() {
		TB_position();
		$("#UP_load").hide();
		$("#previewWin").css({display:"block"});
		$("#PP_footer").css("opacity",100);
		}, product_count);
	
}

//helper functions below

function loadProduct(p_id,url,callback,product_count) {
	sCurrentProduct = p_id;
	if (product_count) 
		iGlobalProductCount = parseInt(product_count);
	$("#PP_ajaxContent").load(url,callback);
	$("#PP_closeWindowButton").attr("innerHTML","x close window"); // set this in case content was changed by size chart
	$("#PP_closeWindowButton").css("color","");
	$("#PP_closeWindowButton").unbind('click');
	$("#PP_closeWindowButton").click( function() { TB_remove(); return false; } );
	
}

function TB_remove() {
	$("#PP_closeWindowButton").unbind("click");
	$("#PP_previousButton").unbind("click");
	$("#PP_nextButton").unbind("click");
	$("#PP_previousButton").unbind("focus");
	$("#PP_nextButton").unbind("focus");

	$("#previewWin").fadeOut("fast",function(){$('#previewWin,#pageOverlay,#UP_HideSelect').trigger("unload").unbind().remove();});
	$("#UP_load").hide();
	$("#product_overlay").hide();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function TB_position() {
$("#previewWin").css({marginLeft: '-' + parseInt((global_previewWidth / 2),10) + 'px', width: global_previewWidth + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#previewWin").css({marginTop: '-' + parseInt((global_previewHeight / 2),10) + 'px'});
	}
}


function positionLoading(container_width,container_height) {
	var load_width = 100;
	var load_height = 100;
	$("#UP_load")
		.css({left: (container_width-load_width)/2, top: (container_height-load_height)/2 })
		.css({display:"block"});
}

/*
function parseQueryString ( query ) {
	if( !query )
		return {};
	var params = {};
	
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}
*/

function showColorInfo(el,color_name, size_range) {
alert('hey');
	//alert("showColorInfo " + $(el).attr("id"));
}

function showColorsPreview(product_id,color_div_id) {
	if (!$('#inner_'+color_div_id).attr("id")) {
		$('#'+color_div_id).append("<div id=\"inner_"+color_div_id+"\"></div>");
		$('#inner_'+color_div_id).load("/catalog/product/colors.asp?p="+product_id+"&r=1"+Math.random());
		//$('#'+color_div_id).load("/catalog/product/colors.asp?p="+product_id);
	} else {
		//alert("already exists!");
	}
	$('#'+color_div_id).show();
}
function hideColorsPreview(color_div_id) {
	$('#'+color_div_id).hide();
}





function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
    var ffversion = new Number(RegExp.$1);
    if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
      return true;
    }
  }
}













/*

function TB_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}

function TB_remove1() {
	//$("#pageOverlay").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#PP_previousButton").unbind("click");
	$("#PP_nextButton").unbind("click");
	$("#PP_previousButton").unbind("focus");
	$("#PP_nextButton").unbind("focus");

	$("#previewWin").fadeOut("fast",function(){$('#pageOverlay').hide();});
	$("#UP_load").remove();
	return false;
}

function showProductColor(product_id, color_code, color_name, size_range) {	
	if ( $("#preview").attr("title") == product_id+'_'+color_code ) return true;
	else $("#preview").attr("title", product_id+'_'+color_code);
	$("#productSizes").attr("innerHTML",'<b>'+color_name + '</b><br>Available in sizes ' + size_range + '.');
	$("#lnkGetQuote").attr("href","javascript:openQuote('"+product_id+"','"+color_code+"')");

	return true;
}

jQuery.fn.extend({
	animateFrom: function( prop, speed, easing, callback, start_x, start_y ) {
		this.css({"left":start_x,"top":start_y});
		return this.queue(function(){
		
			this.curAnim = jQuery.extend({}, prop);
			var opt = jQuery.speed(speed, easing, callback);
			
			for ( var p in prop ) {
				var e = new jQuery.fx( this, opt, p );
				if ( prop[p].constructor == Number )
					e.custom( e.cur(), prop[p] );
				else
					e[ prop[p] ]( prop );
			}
			
		});
	}
})


function right(str, n)
{
		if (n <= 0)     // Invalid bound, return blank string
		   return "";
		else if (n > String(str).length)   // Invalid bound, return
		   return str;                     // entire string
		else { // Valid bound, return appropriate substring
		   var iLen = String(str).length;
		   return String(str).substring(iLen, iLen - n);
		}
}

function left(str, n)
{
		if (n <= 0)     // Invalid bound, return blank string
				return "";
		else if (n > String(str).length)   // Invalid bound, return
				return str;                // entire string
		else // Valid bound, return appropriate substring
				return String(str).substring(0,n);
}

*/
