/*
 * 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
*/

// on page load call TB.init
$(document).ready(
	function() {
		// pass where to apply thickbox
		TB.init('a.thickbox, area.thickbox, input.thickbox');

		// preload image
		TB.imgLoader = new Image();
		TB.imgLoader.src = inportalBase + 'inc/jquery/thickbox/loadingAnimation.gif';
	}
);

function TB () {
	this.imgLoader = null;
	this.pathToImage = inportalBase + 'inc/jquery/thickbox/loadingAnimation.gif';

	this.Width = null;
	this.Height = null;
}

//add thickbox to href & area elements that have a class of .thickbox
TB.init = function (domChunk) {
	$(domChunk).click(
		function() {
			var t = this.title || this.name || null;
			var a = this.href || this.alt;
			var g = this.rel || false;

			TB.show( {caption: t, url: a, imageGroup: g} );
			this.blur();
			return false;
		}
	);
}

// function called when the user clicks on a thickbox link
TB.show = function (params) {

//	caption, url, imageGroup, onDataReceived, onAfterShow, postParams

	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('TB_HideSelect') === null) {
				// iframe to hide select elements in ie6
				$('body').append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$('#TB_overlay').click(TB.remove);
			}
		} else {
			// all others
			if (document.getElementById('TB_overlay') === null) {
				$('body').append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$('#TB_overlay').click(TB.remove);
			}
		}

		if (TB.detectMacXFF()) {
			$('#TB_overlay').addClass('TB_overlayMacFFBGHack'); // use png overlay so hide flash
		} else {
			$('#TB_overlay').addClass('TB_overlayBG'); // use background and opacity
		}

		if (params.caption === null) {
			params.caption = '';
		}

		$('body').append("<div id='TB_load'><img src='" + TB.imgLoader.src + "' /></div>"); // add loader to the page
		$('#TB_load').show(); // show loader

		var baseURL;
		if (params.url.indexOf('?') !== -1) {
			// ff there is a query string involved
			baseURL = params.url.substr(0, params.url.indexOf('?'));
		} else {
			baseURL = params.url;
		}

		var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
		var url_params = {};

		if ( baseURL.toLowerCase().match(urlString) ) {
			TB.processImages(params, urlString);
		} else {
			var queryString = params.url.replace(/^[^\?]+\??/,'');
			url_params = TB.parseQuery(queryString);

			TB.processDialog(params, url_params);
		}

		if (url_params['modal'] != 'true') {
			$(document).bind(
				'keyup',
				function(e){
					if (e.which == 27){
						// close
						TB.remove();
					}
				}
			);
		}
	} catch(e) {
		//nothing here
	}
}

// helper functions below
TB.processImages = function (params, urlString) {
	// code to show images
	var TB_PrevCaption = '';
	var TB_PrevURL = '';
	var TB_PrevHTML = '';
	var TB_NextCaption = '';
	var TB_NextURL = '';
	var TB_NextHTML = '';
	var TB_imageCount = '';
	var TB_FoundURL = false;

	if (params.imageGroup) {
		// scan images in group to create Prev/Next links
		var TB_TempArray = $('a[rel=' + params.imageGroup + ']').get();
		for (var TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === '')); TB_Counter++) {
			var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
			if (!(TB_TempArray[TB_Counter].href == params.url)) {
				if (TB_FoundURL) {
					TB_NextCaption = TB_TempArray[TB_Counter].title;
					TB_NextURL = TB_TempArray[TB_Counter].href;
					TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
				} else {
					TB_PrevCaption = TB_TempArray[TB_Counter].title;
					TB_PrevURL = TB_TempArray[TB_Counter].href;
					TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
				}
			} else {
				TB_FoundURL = true;
				TB_imageCount = 'Image ' + (TB_Counter + 1) + ' of ' + TB_TempArray.length;
			}
		}
	}

	var imgPreloader = new Image();
	$(imgPreloader).bind(
		'load',
		function() {
			$(this).unbind('load');
			var $image_size = TB.scaleImage.call(TB, this);

			TB.Width = $image_size.width + 30;
			TB.Height = $image_size.height + 60;
			$('#TB_window').append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='" + params.url + "' width='" + $image_size.width + "' height='" + $image_size.height + "' alt='" + params.caption + "'/></a>" + "<div id='TB_caption'>" + params.caption + "<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>");
			$('#TB_closeWindowButton').click(TB.remove);

			if (TB_PrevHTML !== '') {
				function goPrev() {
					$('#TB_window').remove();
					$('body').append("<div id='TB_window'></div>");
					TB.show( {caption: TB_PrevCaption, url: TB_PrevURL, imageGroup: params.imageGroup} );
					return false;
				}

				$('#TB_prev').click(goPrev);
			}

			if (TB_NextHTML !== '') {
				function goNext() {
					$('#TB_window').remove();
					$('body').append("<div id='TB_window'></div>");
					TB.show( {caption: TB_NextCaption, url: TB_NextURL, imageGroup: params.imageGroup} );
					return false;
				}

				$('#TB_next').click(goNext);

			}

			$(document).bind(
				'keydown',
				function(e) {
					var keycode = e.which;

					if (keycode == 27) { // close
						TB.remove();
					} else if (keycode == 190) {
						// display previous image
						if (TB_NextHTML != '') {
							$(this).unbind('keydown');
							goNext();
						}
					} else if (keycode == 188) {
						// display next image
						if(TB_PrevHTML != ''){
							$(this).unbind('keydown');
							goPrev();
						}
					}
				}
			);

			// show image after it's loaded
			TB.position();
			$('#TB_load').remove();
			$('#TB_ImageOff').click(TB.remove);
			$('#TB_window').css('display', 'block'); // for safari using css instead of show
		}
	);

	imgPreloader.src = params.url;
}

TB.scaleImage = function ($image) {
	// resizing large images - orginal by Christian Montoya edited by me
	var pagesize = TB.getPageSize();
	var x = pagesize[0] - 150;
	var y = pagesize[1] - 150;

	var imageWidth = $image.width;
	var imageHeight = $image.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;
		}
	}

	return {width: imageWidth, height: imageHeight};
}

TB.processDialog = function (params, url_params) {
	// code to show html

	// window size is global
	TB.Width = (url_params['width'] * 1) + 30 || 630; // defaults to 630 if no paramaters were added to URL
	TB.Height = (url_params['height'] * 1) + 40 || 440; // defaults to 440 if no paramaters were added to URL

	var ajaxContentW = TB.Width - 30;
	var ajaxContentH = TB.Height - 45;

	if (params.url.indexOf('TB_iframe') != -1) {
		// either iframe or ajax window
		urlNoQuery = params.url.split('TB_');
		$('#TB_iframeContent').remove();

		if (url_params['modal'] != 'true') {
			// iframe no modal
			$('#TB_window').append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + params.caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='TB.showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' > </iframe>");
		}else{
			// iframe modal
			$('#TB_overlay').unbind();
			$('#TB_window').append("<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='TB.showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
		}
	} else {
		// not an iframe, ajax
		if ($('#TB_window').css('display') != 'block') {
			if (url_params['modal'] != 'true') {
				// ajax no modal
				$('#TB_window').append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + params.caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>");
			} else {
				// ajax modal
				$('#TB_overlay').unbind();
				$('#TB_window').append("<div id='TB_ajaxContent' class='TB_modal' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>");
			}
		} else {
			// this means the window is already up, we are just loading new content via ajax
			$('#TB_ajaxContent')[0].style.width = ajaxContentW + 'px';
			$('#TB_ajaxContent')[0].style.height = ajaxContentH + 'px';
			$('#TB_ajaxContent')[0].scrollTop = 0;
			$('#TB_ajaxWindowTitle').html(params.caption);
		}
	}

	$('#TB_closeWindowButton').click(TB.remove);

	if (params.url.indexOf('TB_inline') != -1) {
		$('#TB_ajaxContent').html( $('#' + url_params['inlineId']).html() );
		$('#TB_window').unload(
			function () {
				// move elements back when you're finished
				$('#' + url_params['inlineId']).html( $('#TB_ajaxContent').html() );
			}
		);

		TB.position();
		$('#TB_load').remove();
		$('#TB_window').css('display', 'block');
	} else if (params.url.indexOf('TB_iframe') != -1) {
		TB.position();

		if ($.browser.safari) {
			// safari needs help because it will not fire iframe onload
			$('#TB_load').remove();
			$('#TB_window').css('display', 'block');
		}
	} else {
		var $content_url = params.url + '&random=' + (new Date().getTime());

		if (params.postParams === undefined) {
			$.get(
				$content_url,
				function ($data) {
					TB.onDataReceived($data, params);
				}
			);
		}
		else {
			$.post(
				$content_url,
				params.postParams,
				function ($data) {
					TB.onDataReceived($data, params);
				}
			);
		}

		/*$('#TB_ajaxContent').load(
			params.url += '&random=' + (new Date().getTime()),
			params.postParams,
			function() {
				//to do a post change this load method
				TB.position();
				$('#TB_load').remove();
				TB.init('#TB_ajaxContent a.thickbox');
				$('#TB_window').css('display', 'block');

				if ( $.isFunction(params.showCallback) ) {
					params.showCallback();
				}
			}
		);*/
	}
}

TB.parseRedirect = function ($data) {
	var $match_redirect = new RegExp('^#redirect#(.*)').exec($data);
	if ($match_redirect != null) {
		// redirect to external template requested
		return $match_redirect[1];
	}

	return false;
}

TB.onDataReceived = function ($data, $params) {
	if ( $.isFunction($params.onDataReceived) ) {
		$data = $params.onDataReceived($data);
		if ($data === false) {
			// this callback even could prevent redirect action
			// callback requested to stop processing
			return ;
		}
	}

	var $redirect = TB.parseRedirect($data);
	if ($redirect !== false) {
		window.location.href = $redirect;
		return ;
	}

	$('#TB_ajaxContent').html($data);

	TB.position();
	$('#TB_load').remove();
	TB.init('#TB_ajaxContent a.thickbox');
	$('#TB_window').css('display', 'block');

	if ( $.isFunction($params.onAfterShow) ) {
		$params.onAfterShow();
	}
}

TB.showIframe = function () {
	$('#TB_load').remove();
	$('#TB_window').css('display', 'block');
}

TB.remove = function () {
 	$('#TB_imageOff').unbind('click');
	$('#TB_closeWindowButton').unbind('click');

	$('#TB_window').fadeOut(
		'fast',
		function(){
			$('#TB_window,#TB_overlay,#TB_HideSelect').trigger('unload').unbind().remove();
		}
	);

	$('#TB_load').remove();
	if (typeof document.body.style.maxHeight == 'undefined') {
		// if IE 6
		$('body','html').css( {height: 'auto', width: 'auto'} );
		$('html').css('overflow', '');
	}

	$(document).unbind('keydown').unbind('keyup');

	return false;
}

TB.position = function () {
	$('#TB_window').css( {marginLeft: '-' + parseInt((TB.Width / 2), 10) + 'px', width: TB.Width + 'px'} );

	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) {
		// take away IE6
		$('#TB_window').css( {marginTop: '-' + parseInt((TB.Height / 2), 10) + 'px'} );
	}
}

TB.parseQuery = function (query) {
	var Params = {};
	if (!query) {
		// return empty object
		return Params;
	}

	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;
}

TB.getPageSize = function () {
	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;

	return [w, h];
}

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

	return false;
}


