/*
 * UI-dialog 0.1 for GigaCast
 * By Martin 'Smasty' Šrank (http://smasty.net)
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Original: Thickbox 3.1 by Cody Lindley (http://www.codylindley.com)
*/
		  
var ui_pathToImage = "dialog/img/loader.gif";

/*!!!!!!!!!!!!!!!!! EDIT BELOW THIS LINE AT YOUR OWN RISK !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call ui_init
$(document).ready(function(){   
	ui_init('a.ui-dialog, area.ui-dialog, input.ui-dialog');//pass where to apply ui-dialog
	imgLoader = new Image();// preload image
	imgLoader.src = ui_pathToImage;
});

//add ui-dialog to href & area elements that have a class of .ui-dialog
function ui_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	if(this.href.indexOf('?')!=-1){
	  var a = this.href+'&width=800&height=450' || this.alt;
	}
	else{
	  var a = this.href+'?width=800&height=450' || this.alt;
	}
	var g = this.rel || false;
	ui_show(t,a,g);
	this.blur();
	return false;
	});
}

function ui_show(caption, url, imageGroup) {//function called when the user clicks on a ui-dialog 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("UI_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='UI_HideSelect'></iframe><div id='UI_overlay'></div><div id='UI_window'></div>");
			}
		}else{//all others
			if(document.getElementById("UI_overlay") === null){
				$("body").append("<div id='UI_overlay'></div><div id='UI_window'></div>");
			}
		}
		
		if(ui_detectMacXFF()){
			$("#UI_overlay").addClass("UI_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#UI_overlay").addClass("UI_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='UI_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#UI_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$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){
      UI_PrevCaption = "";
			UI_PrevURL = "";
			UI_PrevHTML = "";
			UI_NextCaption = "";
			UI_NextURL = "";
			UI_NextHTML = "";
			UI_imageCount = "";
			UI_FoundURL = false;

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = ui_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
			
			UI_WIDTH = 800;
			UI_HEIGHT = 450;
			$("#UI_window").append("<div id='UI_topline'><div id='UI_caption'>"+caption+"</div><div id='UI_closeWindow'><a href='#' id='UI_closeWindowButton' title='Close'></a></div></div><img id='UI_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/>" + "<div id='UI_secondLine'>" + UI_imageCount + UI_PrevHTML + UI_NextHTML + "</div>"); 		
			
			$("#UI_closeWindowButton").click(ui_remove);
			
			if (!(UI_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#UI_window").remove();
					$("body").append("<div id='UI_window'></div>");
					ui_show(UI_PrevCaption, UI_PrevURL, imageGroup);
					return false;	
				}
				$("#UI_prev").click(goPrev);
			}
			
			if (!(UI_NextHTML === "")) {		
				function goNext(){
					$("#UI_window").remove();
					$("body").append("<div id='UI_window'></div>");
					ui_show(UI_NextCaption, UI_NextURL, imageGroup);				
					return false;	
				}
				$("#UI_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					ui_remove();
				} else if(keycode == 190){ // display previous image
					if(!(UI_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(UI_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			ui_position();
			$("#UI_load").remove();
			$("#UI_ImageOff").click(ui_remove);
			$("#UI_overlay").click(ui_remove);
			$("#UI_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 = ui_parseQuery( queryString );

			UI_WIDTH = (params['width']*1) + 30;
			UI_HEIGHT = (params['height']*1) + 40;
			ajaxContentW = UI_WIDTH - 30;
			ajaxContentH = UI_HEIGHT - 45;
			
			if(url.indexOf('UI_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('UI_');
					$("#UI_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#UI_window").append("<div id='UI_title'><div id='UI_ajaxWindowTitle'>"+caption+"</div><div id='UI_closeAjaxWindow'><a href='#' id='UI_closeWindowButton' title='Close'></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='UI_iframeContent' name='UI_iframeContent"+Math.round(Math.random()*1000)+"' onload='ui_showIframe()'> </iframe>");
					}else{//iframe modal
					$("#UI_overlay").unbind();
						$("#UI_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='UI_iframeContent' name='UI_iframeContent"+Math.round(Math.random()*1000)+"' onload='ui_showIframe()'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#UI_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#UI_window").append("<div id='UI_title'><div id='UI_ajaxWindowTitle'>"+caption+"</div><div id='UI_closeAjaxWindow'><a href='#' id='UI_closeWindowButton'></a></div></div><div id='UI_ajaxContent'></div>");
						}else{//ajax modal
						$("#UI_overlay").unbind();
						$("#UI_window").append("<div id='UI_ajaxContent' class='UI_modal'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#UI_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#UI_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#UI_ajaxContent")[0].scrollTop = 0;
						$("#UI_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#UI_closeWindowButton").click(ui_remove);
			
				if(url.indexOf('UI_inline') != -1){	
					$("#UI_ajaxContent").append($('#' + params['inlineId']).children());
					$("#UI_window").unload(function () {
						$('#' + params['inlineId']).append( $("#UI_ajaxContent").children() ); // move elements back when you're finished
					});
					ui_position();
					$("#UI_load").remove();
					$("#UI_window").css({display:"block"}); 
				}else if(url.indexOf('UI_iframe') != -1){
					ui_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#UI_load").remove();
						$("#UI_window").css({display:"block"});
					}
				}else{
					$("#UI_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						ui_position();
						$("#UI_load").remove();
						ui_init("#UI_ajaxContent a.ui-dialog");
						$("#UI_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					ui_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function ui_showIframe(){
	$("#UI_load").remove();
	$("#UI_window").css({display:"block"});
}

function ui_remove() {
 	$("#UI_imageOff").unbind("click");
	$("#UI_closeWindowButton").unbind("click");
	$("#UI_window").fadeOut("fast",function(){$('#UI_window,#UI_overlay,#UI_HideSelect').trigger("unload").unbind().remove();});
	$("#UI_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 false;
}

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

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


