/*
 * 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
 
 ################# New Additions/Changes ###########################
 
 * Version modified 11/7/2008 for Precor Inc. via Engine Interactive
 * Author: Jeffrey Smith jlsmith@privilogic.com
 * Note - PCTB = Precor Custom ThickBox
*/

var pctb_pathToImage = "/images/loadingAnimation.gif";
var pctb_pathToArrowUp = "/images/pctb_arrow_up.png";
var pctb_pathToArrowDown = "/images/pctb_arrow_down.png";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call pctb_init
$(document).ready(function(){   
	pctb_init('a.pctb'); //pass where to apply pctb
	imgLoader = new Image();// preload image
	imgLoader.src = pctb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function pctb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title;
	var a = this.href;
	var o = this;
	// var g = this.rel || false;
	pctb_show(t,a,o); // removed 'g' param from call and ImgGroup param from function
	this.blur();
	return false;
	});
}

function pctb_show(caption, url, oCaller) {//function called when the user clicks on a pctb link
	// try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("PCTB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='PCTB_HideSelect'></iframe><div id='PCTB_overlay'></div><div id='PCTB_windowCont'><div id='PCTB_window'></div></div>");
				$("#PCTB_overlay").click(pctb_remove);
			}
		}else{//all others
			if(document.getElementById("PCTB_overlay") === null){
				$("body").append("<div id='PCTB_overlay'></div><div id='PCTB_windowCont'><div id='PCTB_window'></div></div>");
				$("#PCTB_overlay").click(pctb_remove);
			}
		}
		
		// Mac FF hack
		if(pctb_detectMacXFF()){
			$("#PCTB_overlay").addClass("PCTB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#PCTB_overlay").addClass("PCTB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		// Add Loader if necessary
		$("body").append("<div id='PCTB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#PCTB_load').show();//show loader
		
		// Get Base URL of element ('#PCTB_Inline')
		var baseURL;
	    if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	    }else{ 
	   		baseURL = url;
	    }
		
		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = pctb_parseQuery( queryString );
		
		// PCTB_WIDTH = ($('#'+params['inlineId']).outerWidth()) + 30;
		PCTB_HEIGHT = ($('#'+params['inlineId']).outerHeight() < 188) ? 188 : 477; // background height +50
		PCTB_WIDTH = 284;
		// PCTB_HEIGHT = 480; 
		ajaxContentW = PCTB_WIDTH - 30;
		ajaxContentH = PCTB_HEIGHT - 45;
		// not an iframe, ajax
		if($("#PCTB_windowCont").css("display") != "block"){
			$("#PCTB_window").append("<div id='PCTB_title'><div id='PCTB_ajaxWindowTitle'>"+caption+"</div><div id='PCTB_closeAjaxWindow'><a href='#' id='PCTB_closeWindowButton'></a></div></div><div id='PCTB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'><div style='clear:both'></div></div>");
		}else{//this means the window is already up, we are just loading new content via ajax
			$("#PCTB_ajaxContent")[0].style.width = ajaxContentW +"px";
			$("#PCTB_ajaxContent")[0].style.height = ajaxContentH +"px";
			$("#PCTB_ajaxContent")[0].scrollTop = 0;
			$("#PCTB_ajaxWindowTitle").html(caption);
		}
		$("#PCTB_closeWindowButton").click(pctb_remove);
		
		// Add Arrow to window
		$("#PCTB_window").append("<div id=\"PCTB_window_arrow\"></div>");

		
		/*if(url.indexOf('PCTB_inline') != -1){	*/
			$("#PCTB_ajaxContent").append($('#' + params['inlineId']).children());
			$("#PCTB_windowCont").unload(function () {
				$('#' + params['inlineId']).append( $("#PCTB_ajaxContent").children() ); // move elements back when you're finished
			});
			pctb_position(oCaller,params['xAlign'],params['yAlign']);
			$("#PCTB_load").remove();
			$("#PCTB_windowCont").css({display:"block"}); 
		/*}else if(url.indexOf('PCTB_iframe') != -1){
			pctb_position(oCaller,params['xAlign'],params['yAlign']);
			if($.browser.safari){//safari needs help because it will not fire iframe onload
				$("#PCTB_load").remove();
				$("#PCTB_windowCont").css({display:"block"});
			}
		}else{
			$("#PCTB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
				pctb_position(oCaller,params['xAlign'],params['yAlign']);
				$("#PCTB_load").remove();
				pctb_init("#PCTB_ajaxContent a.pctb");
				$("#PCTB_windowCont").css({display:"block"});
			});
		}*/

		// Set event handler to reposition the div correctly on scroll and resize
		$(window).scroll( function() {
			document.title = pctb_position(oCaller,params['xAlign'],params['yAlign']);
		});
		$(window).resize( function() {
			pctb_position(oCaller,params['xAlign'],params['yAlign']);
		});
	/*} catch(e) {
		//nothing here
		alert("catch error");
	}*/
}

//helper functions below
function pctb_showIframe(){
	$("#PCTB_load").remove();
	$("#PCTB_windowCont").css({display:"block"});
}

function pctb_remove() {
 	$("#PCTB_imageOff").unbind("click");
	$("#PCTB_closeWindowButton").unbind("click");
	$('PCTB_window_arrow').remove();
	$("#PCTB_windowCont").fadeOut("fast",function(){$('#PCTB_windowCont,#PCTB_overlay,#PCTB_HideSelect').trigger("unload").unbind().remove();});
	$("#PCTB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	// remove bound events to window for resize & scroll
	$(window).unbind('scroll');
	$(window).unbind('resize');
	return false;
}

function pctb_position(objCaller,xAlign,yAlign) {
	// Set conditional for IE6
	var isIE6 = (jQuery.browser.msie && jQuery.browser.version < 7) ? true : false;
	var x,y,arrowX,arrowY,shadowXOffset;
	var ie6YOffset = 0;// 55;
	
	// Default thickbox positioning
	// $("#PCTB_window").css({marginLeft: '-' + parseInt((PCTB_WIDTH / 2),10) + 'px', width: PCTB_WIDTH + 'px'});
	
	// set new location based upon object calling	
	var arrowWidth = 7; // Set to half of the arrow width to align properly
	var arrowHeight = 12; // Set to full arrow height to align properly
	var shadowXOffset = 15 // default to 15
	var arrowImg = pctb_pathToArrowUp; // Default to arrow pointing up
	var topOffset = $(window).scrollTop();
	var leftOffset = $(window).scrollLeft();
	
	// Set window and window arrow based upon 
	switch(xAlign) {
		case "left":
			x = ($(objCaller).position().left) + shadowXOffset;
			arrowX = ($(objCaller).outerWidth() / 2) - arrowWidth - shadowXOffset;
		break;
		case "right":
			x = ($(objCaller).position().left + $(objCaller).outerWidth()) - $("#PCTB_windowCont").outerWidth() + shadowXOffset;
			arrowX = $("#PCTB_windowCont").outerWidth() - (($(objCaller).outerWidth() / 2) + arrowWidth) - shadowXOffset;
		break;
		default: // default 'center' align
			x = $(objCaller).position().left + ($(objCaller).outerWidth() / 2) - ($("#PCTB_windowCont").outerWidth() / 2) + shadowXOffset;
			arrowX = ($("#PCTB_windowCont").outerWidth() / 2) - arrowWidth - shadowXOffset;
		break;
	}
	switch(yAlign) {
		// figure out whether window should be on top or bottom
		case "top":
			y = ($(objCaller).position().top) - ($("#PCTB_windowCont").outerHeight()) - topOffset + ie6YOffset; // removed arrowHeight height from calc
			arrowY = $("#PCTB_windowCont").outerHeight() - 14;
			arrowImg = arrowImg = "url('" + pctb_pathToArrowDown + "')";
			// Determine which background to show based on generated height
			if($("#PCTB_windowCont").outerHeight() > 188)
				$("#PCTB_window").css({backgroundImage:"url('/images/overlay_topbg-lg.png')",height:"480px"});
			else
				$("#PCTB_window").css({backgroundImage:"url('/images/overlay_topbg-sm.png')",height:"188px"});
		break;
		default: // default 'bottom' align
			y = ($(objCaller).position().top) + ($(objCaller).innerHeight() + arrowHeight) - topOffset + ie6YOffset;
			arrowY = 0 - (arrowHeight-5);
			arrowImg = "url('" + pctb_pathToArrowUp + "')";
		break;
	}
	$("#PCTB_windowCont").css({ marginTop:"0", marginLeft:"0", top:y, left:x }); // remove centering styles after repositioning
	// alert($("#PCTB_windowCont").css("width") + ": " + $("#PCTB_windowCont").css("height"));
	if(isIE6){ $("#PCTB_window").css({width:$("#PCTB_windowCont").css("width"),height:$("#PCTB_windowCont").css("height")});} // reset the inner div to match the container (for IE6)
	// alert($(objCaller).position().top + ":" + topOffset + ":" + y + ":" + $("#PCTB_window").css("margin-top"));
	$("#PCTB_window_arrow").css({top:arrowY,left:arrowX,backgroundImage:arrowImg });
	// Assign PNG fix to specific divs
	if(isIE6){
		$("#PCTB_window").ifixpng();
		$("#PCTB_window_arrow").ifixpng();
	}
	return window.pageYOffset;
}

function pctb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function pctb_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 = [w,h];
	return arrayPageSize;
}

function pctb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


