/*
 * Main Function.  Called when dom is ready.
 */
loadimg = new Image;
loadimg.src = "/common/images/loader.gif";
$jQ(function() {
	$jQ('a.photo-popup-link').bind("mouseover",showImage); //popup images
	$jQ('a.tag-pop-link').bind("click",showTag); //popup tag this item links
	$jQ('a.grande-details').bind("click",showGrande);
	$jQ('.go-count-jump').bind("change",function() { //items per page menu
		$jQ(this).parents("form")[0].submit();
	});
	
	//$jQ('a[href$="xmas.shipping"]') .attr("target",""); 
	//$jQ('a[href$="xmas.shipping"]') .attr("href",SelfPage+"?go=xmas.shippingpop&amp;height=300"); 
});

var timeout = new Object(); // used to check if item image is rolled off
/**
 * Callback function for showing image popup
 * this Object is jQuery Object containing calling element.
 * @param {Object} e Event that is passed through callback
 */
function showImage(e) {
	if(timeout[this.id]) {clearTimeout(timeout[this.id]);}
	addPop(this.id, this.href, this.title, $jQ(this).attr("rel"));
	$jQ('a[id="'+this.id+'"]').attr("href","#");
	// keep image on screen
	$jQ('a[id="'+this.id+'"]').click(function() {		
		return false;
	});
	
	$jQ('#'+this.id).prev().children().show(2);
	$jQ('#'+this.id).prev().show(2);
	//$jQ('#po-'+this.id).children('.photo-popup').ScrollTo(800);
	$jQ(this).bind("mouseout",hideImage);	
}

function keepImage() {
	timeVar = $jQ(this).parents(".photo-popup-outer").next().attr("id");
	if(timeout[timeVar]) {clearTimeout(timeout[timeVar]);}
	$jQ(this).bind("mouseout",function() {
		if(timeout[timeVar]) {clearTimeout(timeout[timeVar]);}
		timeout[timeVar] = setTimeout("hideit('"+timeVar+"')",250);	
	});
}
/** 
 * Calback for hiding images.
 * this Object is jQuery Object containing calling element.
 * @param {Object} e Event that is passed through callback.
 */
function hideImage(e) {
	timeout[this.id] = setTimeout("hideit('"+this.id+"')",250);	
}

function hideit(itemid) {
	
	/*
		IE under 7 can't figure out how to hide the
		pointer for some reason.  Luckily this step
		is only REALLY needed for Safari.
	 */
	if( !$jQ.browser.msie) {
		$jQ('#'+itemid).prev().children().hide(2);
	}
	
	/* 
		Older versions of Safari break when the object 
		gets hidden for some reason.  Try to find out if
		this is Safari before version 3.  If it is then
		don't hide the object.  
		
		Safari prior to version 3 doesn't have "Version"
		in the UserAgent String.
	*/
	if(!($jQ.browser.safari && (navigator.userAgent.toLowerCase().match(/.+on[\/ ]([\d.]+)/) || []).length)) {
		$jQ('#'+itemid).prev().hide("normal");
	};
	 
}

/**
 * Callback function for showing tagging popup
 * this Object is jQuery Object containing calling element.
 * @param {Object} e Event that is passed through callback
 */
function showTag(e) {
	hideTags();
	if($jQ('#tpo-'+this.id).length  == 0) {
		addTagPop(this.id);
		$jQ('a[id="'+this.id+'"]').attr("href","#");
	}
	var presid = this.id.replace(/tag-/,"");
	
	$jQ('#tpo-'+this.id).show(2, function() {
		// reposition the window
		p = jQuery.getPos($jQ('#tag-'+presid)[0]); 
		c = jQuery.getClient();
		//console.log(p.x);
		if(c.w < 1000) {c.w = 1000}; 
		loc = (((c.w/2) + p.x)/2);
		//add the div differently depending on who's looking, sniff.
		if($jQ.browser.safari || $jQ.browser.opera) { 	
			$jQ('#tpo-'+presid).find('.tag-pop-saf').css("left",parseInt(loc-(c.w-p.x))+"");
		
		console.log($jQ('#tpo-'+presid).find('.tag-pop-saf').css("left"));
		}
		else {
			// this part makes me sad
			if($jQ.browser.msie && parseFloat(navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/)[1]) < 7) {
				$jQ('#tpo-tag-'+presid).find('.tag-pop').css("left",42);
			} else {
				$jQ('#tpo-tag-'+presid).find('.tag-pop').css("left",loc-(c.w-p.x));
			}
		}
		//end repositioning
	});
	
	
	var thisid = this.id;
	// IE needs the zoom set back to normal because jQuery sets it to 1
	$jQ('#tpo-'+this.id).show("2",function() {document.getElementById('tpo-'+thisid).style.zoom = 'normal';});
	
	$jQ('#tc-'+presid).ScrollTo(800);
	$jQ.post(SelfPage,{go:"tags.addtagpop", pid:this.id.replace(/tag-/,"")}, function(data) {
		$jQ('#tc-'+presid).html(data);
		$jQ('#tag-form-'+presid).bind("submit",actTag);
		$jQ('.tag-close').unbind("click");
		$jQ('.tag-close').bind("click",hideTags);
		
		// for some reason IE doesn't work unless both of these happen
		$jQ('#tag-form-'+presid).children('input[type="text"]')[0].focus();
		document.getElementById('tags-'+presid).focus();
	});
	return false;
}

/** 
 * Calback for hiding all tag popups.
 */
function hideTags() {
	if(arguments.length) {
		jReturn = arguments[0];
		if(!$jQ('#span-'+jReturn.pid).children('a').length) {  // we dont have tags
			$jQ('#span-'+jReturn.pid).css("display","");
		}
		if(jReturn.taggood == 1) {
			$jQ('#span-'+jReturn.pid).children('a').remove();
			$jQ('#span-'+jReturn.pid).children('span').remove();
			for( tag in jReturn.tags) {
				$jQ('#span-'+jReturn.pid+' em').after('<a href="/index.cfm/go/front.tagged/tag/'+jReturn.tags[tag]+'" >'+jReturn.tags[tag]+'</a> ');
			}; 
			$jQ('#span-'+jReturn.pid).children('a').fadeTo("fast", 0.0).fadeTo("fast", 0.7).fadeTo("fast", 0.3).fadeTo("fast", 1);
		} else {
			$jQ('#span-'+jReturn.pid).children('a').remove();
			$jQ('#span-'+jReturn.pid).children('span').remove();
			$jQ('#span-'+jReturn.pid+' em').after('<span style="color:#900;">There was an error adding your tag.</span> ');
			$jQ('#span-'+jReturn.pid).children('span').fadeTo("fast", 0.0).fadeTo("fast", 0.7).fadeTo("fast", 0.3).fadeTo("fast", 1);
		};
	};
	$jQ('.tag-popup-outer').css("display","none");
	$jQ('.tag-popup-outer-saf').hide();
	return false;
}

/**
 * Create the image popup
 * @param {Object} eid itemid
 * @param {Object} ehref link to image
 * @param {Object} etitle title of image
 * @param (string) the max dimension of the image (ie: width=100, height=90)
 */
function addPop(eid,ehref,etitle,eDimen) {
	if(z) {delete z;}
	var	z = new Object();
	
	if($jQ('#po-'+eid).length  == 0) {
	
		var imgParams = {src: ehref, style: 'border:0px;', alt: etitle }
		
		if (eDimen != null && eDimen.length) {
			var ary = eDimen.split("=");
			if (ary.length == 2 && ary[0] == 'width') imgParams = {src: ehref, style: 'border:0px;', alt: etitle, width: ary[1] }
			else if  (ary.length == 2 && ary[0] == 'height') imgParams = {src: ehref, style: 'border:0px;', alt: etitle, height: ary[1] }
		}	
	
		$jQ('a[id="'+eid+'"]').parent().createPrepend(
			'div', {className:'photo-popup-outer', id:'po-'+eid },
			[
				'div', {className:'photo-popup'},
				[
					'div',{className:'photo-popup-innerwrap' },
					[
						'div',{className:"photopopup-center-outer" },
						[
							'div',{className:"photopopup-center-middle" },
							[
								'div',{className:"photopopup-center-inner" },
								[
									'h1',{style:"text-align:center;" }, etitle,
									'img',imgParams
								]
							]
						]
					]
				],
				'div', {className:'photo-popup-pointer'},''
			]
		)
	}
	
	$jQ('#po-'+eid).show("0",function() {
		
		$jQ('#po-'+eid).children(".photo-popup").css("bottom",-150); //reset
		$jQ('#po-'+eid).children(".photo-popup-pointer").css("bottom",-170); //reset
		z.s = jQuery.getScroll();
		z.c = jQuery.getClient();
		z.p = jQuery.getPos($jQ('#po-'+eid).find('.photo-popup')[0]);
		if(z.p.y < z.s.t && z.p.y != 0) { // move down, it's too high
			objTop = (-120-(z.s.t-z.p.y));
			pbottom = -170;
		} else if(z.p.y + z.p.h > z.s.t+z.c.h && z.p.y != 0) {  // move up, it's too low
			objTop = (-160+(z.p.y + z.p.h) - (z.s.t+z.c.h));
			pbottom = -140;
		} else { // it's just right
			objTop = -170;
			pbottom = -170;
		}
		$jQ('#po-'+eid).children(".photo-popup").css("bottom",objTop); 
		$jQ('#po-'+eid).children(".photo-popup-pointer").css("bottom",pbottom); 
		$jQ('#po-'+eid).show(2);
		
	});
	
	$jQ('#po-'+eid).find('div').bind('mouseover',keepImage).end().find('img').bind('mouseover',keepImage);
	return z;
}

/**
 * Create the tag popup
 * @param {Object} eid itemid
 */
function addTagPop(eid) {
	// try to find where to put the div
	p = jQuery.getPos($jQ('#'+eid)[0]); 
	c = jQuery.getClient();
	if(c.w < 1000) {c.w = 1000}; 
	loc = (((c.w/2) + p.x)/2);
	//add the div differently depending on who's looking, sniff.
	if($jQ.browser.safari || $jQ.browser.opera) { 	
		$jQ('#'+eid).parent().parent().createAppend(
			'div',{className:'tag-popup-outer-saf',id:'tpo-'+eid },
			[
				'div', {style:'position:absolute' }, 
				[
					'div', {className:'tag-pop-saf' }, 
					[
						'div', {className:'tag-pop-contents',id:'tc-'+eid.replace(/tag-/,"") },
						[
							'img', {src:"/common/images/ajax-loader-sm-cream.gif",style:"margin:70px 0px 0px 95px"},[]
						]
					],
					'div', {className:'tag-pop-pointer-saf'},""
				],
				'img', {src:'/common/images/tag-popup-pointer.png',className:'saf' }
			]
		);
	
	$jQ('#tpo-'+eid).find('.tag-pop-saf').css("left",parseInt(loc-(c.w-p.x)+""));
	console.log($jQ('#tpo-'+eid).find('.tag-pop-saf').css("left"));
	}
	else {
		$jQ('#'+eid).parent().parent().createAppend(
			'div',{className:'tag-popup-outer',id:'tpo-'+eid},
			[
				'div',{style:'position:absolute;'},
				[
					'div', {className:'tag-pop' }, [
						'div', {className:'tag-pop-contents',id:'tc-'+eid.replace(/tag-/,'')},
						[
							'img', {src:"/common/images/ajax-loader-sm-cream.gif",style:"margin:70px 0px 0px 95px"},[]
						]
					],
					'div', {className:'tag-pop-pointer'},
					[
						'img', {src:'/common/images/tag-popup-pointer.png'}
					]
				]
			]
		);
		// this part makes me sad
		//parseFloat((navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/)||[])[1]) 
		if($jQ.browser.msie && parseFloat($jQ.browser.version) < 7) {
			$jQ('#tpo-'+eid).find('.tag-pop').css("left",42);
		} else {
			$jQ('#tpo-'+eid).find('.tag-pop').css("left",loc-(c.w-p.x));
		}
	}
}
/**
 * Submit the tag to be added to DB
 */
function actTag() {
	var urlParams = $jQ(this).children().serialize(); // create the form submit string	
	$jQ(this).parents('.tag-pop-contents').html('<img src="/common/images/ajax-loader-sm-cream.gif" style="margin:70px 0px 0px 95px" />');
	$jQ.ajax({
		type: "POST",
		url: SelfPage,
		data: "go=tags.actaddTagpop&"+urlParams,
		dataType:"json",
		success: hideTags
	});
	
	return false;
}

function showGrande(e) {
	hideGrande(e);
	var el = $jQ(this);
	var itemNo = el.attr("href").split("/item/")[1];
	if(itemNo ) {
		if($jQ('#grande-pop-bubble-'+itemNo).length) {
			$jQ('#grande-pop-bubble-'+itemNo).show();
			$jQ("body").click(hideGrande);
			$jQ("body").keypress(hideGrande);
		} else {
			$jQ.ajax( {
				type: "POST",
				url: SelfPage,
				data: "go=misc.grandepop&item="+itemNo,
				success: function(data) {
					el.before(data);
					$jQ("body").click(hideGrande);
					$jQ("body").keypress(hideGrande);
					$jQ('#grande-pop-bubble-'+itemNo).find("*").unbind('click');
					$jQ('#grande-pop-bubble-'+itemNo).find("a").bind('click',function(e) {hideGrande(e);return false;});
				}
			})
		}
	};
	
	return false;
}

function hideGrande(e) {
	$jQ("body").unbind();
	if(e.type == "keypress" && e.keyCode != 27) {
		return true;
	}
	$jQ('.grande-pop-bubble').hide();
	return false;
}

