/*
 * Powered by 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
*/

var vz_pathToLoadImage = "images/common/loadingAnimation.gif";
var vz_pathToHeadBackground = "../images/bg_grid_head.jpg";
var vz_pathToCloseImage = "images/common/bullet_delete.gif";

var default_width = 900;
var default_height = 520;

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

//on page load call vz_init
$(document).ready(function(){   
	vz_init('a.vzbox, area.vzbox, input.vzbox');//pass where to apply vzbox
	imgLoader = new Image();// preload image
	imgLoader.src = vz_pathToLoadImage;
});

//add vzbox to href & area elements that have a class of .vzbox
function vz_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	vz_show(t,a,g);
	this.blur();
	return false;
	});
}

function vz_show(caption, url, imageGroup) {//function called when the user clicks on a vzbox 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("VZ_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='VZ_HideSelect'></iframe><div id='VZ_overlay'></div><div id='VZ_window'></div>");
				$("#VZ_overlay").click(vz_remove);
			}
		}else{//all others
			if(document.getElementById("VZ_overlay") === null){
				$("body").append("<div id='VZ_overlay'></div><div id='VZ_window'></div>");
				$("#VZ_overlay").click(vz_remove);
			}
		}
		
		if(vz_detectMacXFF()){
			$("#VZ_overlay").addClass("VZ_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#VZ_overlay").addClass("VZ_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='VZ_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#VZ_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp|\.img$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp' || urlType == '.img'){//code to show images
				
			VZ_PrevCaption = "";
			VZ_PrevURL = "";
			VZ_PrevHTML = "";
			VZ_NextCaption = "";
			VZ_NextURL = "";
			VZ_NextHTML = "";
			VZ_imageCount = "";
			VZ_FoundURL = false;
			if(imageGroup){
				VZ_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (VZ_Counter = 0; ((VZ_Counter < VZ_TempArray.length) && (VZ_NextHTML === "")); VZ_Counter++) {
					var urlTypeTemp = VZ_TempArray[VZ_Counter].href.toLowerCase().match(urlString);
						if (!(VZ_TempArray[VZ_Counter].href == url)) {						
							if (VZ_FoundURL) {
								VZ_NextCaption = VZ_TempArray[VZ_Counter].title;
								VZ_NextURL = VZ_TempArray[VZ_Counter].href;
								VZ_NextHTML = "<span id='VZ_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								VZ_PrevCaption = VZ_TempArray[VZ_Counter].title;
								VZ_PrevURL = VZ_TempArray[VZ_Counter].href;
								VZ_PrevHTML = "<span id='VZ_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							VZ_FoundURL = true;
							VZ_imageCount = "Image " + (VZ_Counter + 1) +" of "+ (VZ_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = vz_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			VZ_WIDTH = imageWidth + 30;
			VZ_HEIGHT = imageHeight + 60;
			$("#VZ_window").append("<a href='' id='VZ_ImageOff' title='Close'><img id='VZ_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='VZ_caption'>"+caption+"<div id='VZ_secondLine'>" + VZ_imageCount + VZ_PrevHTML + VZ_NextHTML + "</div></div><div id='VZ_closeWindow'><a href='#' id='VZ_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#VZ_closeWindowButton").click(vz_remove);
			
			if (!(VZ_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#VZ_window").remove();
					$("body").append("<div id='VZ_window'></div>");
					vz_show(VZ_PrevCaption, VZ_PrevURL, imageGroup);
					return false;	
				}
				$("#VZ_prev").click(goPrev);
			}
			
			if (!(VZ_NextHTML === "")) {		
				function goNext(){
					$("#VZ_window").remove();
					$("body").append("<div id='VZ_window'></div>");
					vz_show(VZ_NextCaption, VZ_NextURL, imageGroup);				
					return false;	
				}
				$("#VZ_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					vz_remove();
				} else if(keycode == 190){ // display previous image
					if(!(VZ_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(VZ_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			vz_position();
			$("#VZ_load").remove();
			$("#VZ_ImageOff").click(vz_remove);
			$("#VZ_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = vz_parseQuery( queryString );

			VZ_WIDTH = (params['width']*1) + 30 || default_width; //defaults to 630 if no paramaters were added to URL
			VZ_HEIGHT = (params['height']*1) + 40 || default_height; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = VZ_WIDTH - 30;
			ajaxContentH = VZ_HEIGHT - 45;
			
			urlNoQuery = url.split('VZ_');
			$("#VZ_iframeContent").remove();
			$("#VZ_overlay").unbind();
			if (params['noc'] == null) {
			    $("#VZ_window").append("<div id='vzboxHead' style='background:#E5EEF7 url(" + vz_pathToHeadBackground + "); height:33px; overflow:hidden;'><img src='" + vz_pathToCloseImage + "' onClick='vz_remove();' style='float:right; padding:8px 10px; cursor:hand;' /><h1 style='margin:0; padding:8px 10px; font-size:18px;'>" + caption + "</h1></div>");
			}
			
			$("#VZ_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='VZ_iframeContent' name='VZ_iframeContent"+Math.round(Math.random()*1000)+"' onload='vz_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					
			$("#VZ_closeWindowButton").click(vz_remove);
			vz_position();
			if($.browser.safari){//safari needs help because it will not fire iframe onload
				$("#VZ_load").remove();
				$("#VZ_window").css({display:"block"});	
				}
			
		}

		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function vz_showIframe(){
	$("#VZ_load").remove();
	$("#VZ_window").css({display:"block"});
}

function vz_remove() {
 	$("#VZ_imageOff").unbind("click");
	$("#VZ_closeWindowButton").unbind("click");
	$("#VZ_window").fadeOut("fast",function(){$('#VZ_window,#VZ_overlay,#VZ_HideSelect').trigger("unload").unbind().remove();});
	$("#VZ_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 = "";
	return "" //return false;
}

function vz_position() {
$("#VZ_window").css({marginLeft: '-' + parseInt((VZ_WIDTH / 2),10) + 'px', width: VZ_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#VZ_window").css({marginTop: '-' + parseInt((VZ_HEIGHT / 2),10) + 'px'});
	}
}

function vz_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 vz_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 vz_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
