/*
 * 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 tb_pathToImage = '/static/images/modalimg/loadingAnimation.gif';
 
//requires that links have different targets to work for image groups
 
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
 
//on page load call tb_init
$(document).ready(function(){		
	//tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	tb_imgLoader = new Image();// preload image
	tb_imgLoader.src = tb_pathToImage;
	tb_init();
});
 
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(){
	domChunk = 'a.thickbox, area.thickbox, input.thickbox';
	$(domChunk).live('click',function(){
		var t = this.title || this.name || null;
		var a = this.href || this.alt;
		var g = this.rel || false;
		var tbclass = this.getAttribute('tbclass');
		var lightclass = this.rev || false; // to give lightbox a class
		tb_show(t,a,g, tbclass, lightclass);
		this.blur();
		return false;
	});
}
 
function tb_destroy(){
	domChunk = 'a.thickbox, area.thickbox, input.thickbox';
	$(domChunk).unbind("click");
}
 
function tb_show(caption, url, imageGroup, lightclass, tbclass) {//function called when the user clicks on a thickbox link
	try {
		// showall is initially set with rev=showall. the elements on its page need to have rel=showall_{category}
		//this handles the case where you are on a show all page and click an image and want to go to the normal view
		//if ($('#tb_lightbox').hasClass('showall')) {
			//tb_remove();
		$('#TB_overlay').remove();
		$('#TB_window').remove();
		//}
		 
		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>");
				//sacha:
				$('#TB_window').addClass(lightclass);
				$('#TB_overlay').click(tb_remove);
				$('#TB_window').click(tb_remove);
			}
		} else {//all others
			if (document.getElementById('TB_overlay') === null) {
				$('body').append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				//sacha:
				$('#TB_window').addClass(tbclass);
				$('#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 (caption === null) { 
			caption = ""; 
		}
		$('body').append("<div id='TB_load'><img src='"+tb_imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		{//code to show html
 
			//count the number of images in the rel link
			TB_PrevURL = '';
			TB_NextURL = '';
			TB_imageCount = '';
			TB_FoundURL = false;
 
			//alert('tb clicked ' +	 caption +' ' +url +' '+ imageGroup +' '+ lightclass);
			if (imageGroup) {
				showall = imageGroup.split('_');
			
				//this handles the case where you are on a show all page and click an image and want to go to the normal view
				if (showall[0] == 'showall') {
					imageGroup = showall.slice(1).join('_');
				} 
				TB_TempArray = $("a[rel="+imageGroup+"]").get();
			
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextURL === "")); TB_Counter++) {
					if (!(TB_TempArray[TB_Counter].href == url)) {						
						if (TB_FoundURL) {
							TB_NextURL = TB_TempArray[TB_Counter].href;
						} else {
							TB_PrevURL = TB_TempArray[TB_Counter].href;
						}
					} else {
						TB_FoundURL = true;
						TB_imageCount = (TB_Counter + 1) + ' / ' + (TB_TempArray.length);
					}
				}
			}
			
			//set according to graham
			pagesize = tb_getPageSize();
			if ( $('#TB_window').hasClass('showall') ) {
				scalefactor = 0.8;
			} else {
        // if ( $('#TB_window').hasClass('image') ) {
					scalefactor = 0.5;
        // } 
			}
 
			tbWidth = pagesize[0] * scalefactor; //- $('#TB_window').width();
			tbHeight = pagesize[1] * scalefactor; //- $('#TB_window').height();
			//ajaxContentW = TB_WIDTH - 30;
			//ajaxContentH = TB_HEIGHT - 45;
			
			// not an iframe, ajax	
			
			//sacha: added the class for the image group
			$('#TB_window').removeClass();
			$('#TB_window').addClass(tbclass);
 
			if ($('#TB_window').css('display') != 'block') {
				$('#TB_window').append("<div id='tb_lightbox'> \
				<div class='tb_left'> \
				<div class='tb_left_top'></div> \
				<div class='tb_left_middle'> \
				<a id='tb_prev_link' class='tb_prev_link' href='#'></a> \
				</div> \
				<div class='tb_left_bottom'></div> \
				</div> \
				<div class='tb_center'> \
				<div class='tb_center_header'></div> \
				<div id='tb_content'></div> \
				<div class='tb_center_footer'></div> \
				</div> \
				<div class='tb_right'> \
				<div class='tb_right_top'> \
				<a id='tb_close' class='tb_close' href='#'></a> \
				</div> \
				<div class='tb_right_middle'> \
				<a id='tb_next_link' class='tb_next_link' href='#'></a> \
				</div> \
				<div class='tb_right_bottom'></div> \
				</div> \
				</div>");
				} else {//this means the window is already up, we are just loading new content via ajax;
					$("#tb_content")[0].scrollTop = 0;
				}
				//add a class to the lightbox
				if (lightclass) {
					$('#tb_lightbox').addClass(lightclass);
				}
 
				//set the arrrows to show, handle clicks or not display
				if (!(TB_PrevURL === '')) {
					function goPrev(){
						if($(document).unbind('click', goPrev)) {
							$(document).unbind('click', goPrev);
						}
						$('#TB_window').remove();
						$('body').append("<div id='TB_window'></div>");
						//sacha:
						tb_show("", TB_PrevURL, imageGroup, false);
						$('#TB_window').addClass('image');
						return false; 
					}
					$('#tb_prev_link').click(goPrev);
				} else {
					$('#tb_prev_link').css({ 'display' : 'none' });
				}			
				
				if (!(TB_NextURL === '')) {		
					function goNext(){
						$('#TB_window').remove();
						$('body').append("<div id='TB_window'></div>");
						//sacha
						tb_show('', TB_NextURL, imageGroup, false);
						$('#TB_window').addClass('image');
						return false; 
					}
					$('#tb_next_link').click( goNext );
				} else {
					$('#tb_next_link').css({ 'display' : 'none' });
				}
			
				//$("#TB_closeWindowButton").click(tb_remove);		
				$('#tb_close').click( tb_remove );
				//$("#tb_content").jScrollPane();
				//jScrollPane({showArrows:true, scrollbarWidth:11, arrowSize:1});
				$('#tb_content').load(url, '', function() {
					$('#TB_load').remove();
					//tb_init();
					$('#TB_window').css({ 'display' : 'block' });
					if ($('#tb_lightbox').hasClass('showall')) {
						tb_position(true);
						// $("#tb_content").jScrollPane({scrollbarWidth:11, topCapHeight:10, bottomCapHeight:10});
					} else {
						tb_position(false);
					}
 
					// scaleImage();
 
					//append div for TB_imageCount
					if (imageGroup) {
						$('#TB_window .caption').append("<div class='counter'>"+TB_imageCount+"</div>");
					}
					tb_scrollTo(url);
				});
			}
 
			//handle left right esc navigation keys
			document.onkeydown = function(e){		
				if (e == null) { // ie
					keycode = event.keyCode;
					} else { // mozilla
						keycode = e.which;
					}
					if (keycode == 27){ // close
						tb_remove();
						} else if (keycode == 39) { // display previous image
							if (!(TB_NextURL == '')) {
								document.onkeydown = '';
								goNext();
							}
							} else if (keycode == 37) { // display next image
								if (!(TB_PrevURL == '')) {
									document.onkeydown = '';
									goPrev();
								}
							}
						};
					} catch(e) {
						//nothing here
					}
				}
 
function sleep(ms) {
	var dt = new Date();
	dt.setTime(dt.getTime() + ms);
	while (new Date().getTime() < dt.getTime());
}
 
function scaleImage() {
	//set the max-height
	var scaler, hscaler, wscaler;
	scaler = hscaler = wscaler = 1.0;
 
	if ( $('#tb_onlyimage').height() > $(window).height() * 0.80 ) {
		hscaler = $(window).height() * 0.80 / $('#tb_onlyimage').height();
	}
	if ($('#tb_onlyimage').width() > $(window).width() * 0.80) {
		wscaler = $(window).width() * 0.80 / $('#tb_onlyimage').width();
	}
	scaler = (wscaler < hscaler) ? wscaler : hscaler;
	//alert(document.getElementById('tb_onlyimage').width);
	//$("#tb_onlyimage").css({height: scaler*$("#tb_onlyimage").height(), width: scaler*$("#tb_onlyimage").width()});
 
}
 
//helper functions below
function tb_showIframe() {
	$('#TB_load').remove();
	$('#TB_window').css({ 'display' : 'block' });
}
 
function tb_remove() {
	$('#TB_imageOff').unbind('click');
	$('#tb_close').unbind('click');
	$('#tb_next_link').unbind('click');
	$('#tb_prev_link').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.onkeydown = '';
	document.onkeyup = '';
	return false;
}
 
function tb_position(resizeHeight) {
	//alert("width " + TB_WIDTH + " height " + TB_HEIGHT);
	$('#TB_window').css({ marginLeft: '-' + parseInt(tbWidth / 2, 10) + 'px', width: tbWidth + 'px' });
	//if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$('#TB_window').css({ marginTop: '-' + parseInt(tbHeight / 2) + 'px' });
		if ( $('#TB_window').hasClass('showall') ) {
			$('#tb_content').css({ 'height' : parseInt(tbHeight * .8) + 'px'});
			$('#TB_window').css({ marginTop: '-' + parseInt(tbHeight / 4) + 'px' });
			$('#TB_window #tb_content div ul li.listview:nth-child(5n)').css('margin-right', 0);			
			
			if( $('#TB_window #tb_content ul.tabs li.first').hasClass('activetab')){
				tbheader = 141;
			}
			else
				tbheader = 90;
			$('#TB_window #tb_content div.listWrapper').css({'height' : parseInt(tbHeight * .8)-tbheader + 'px', 'margin-bottom': 0 + 'px' });

		}
	//}
}
 
function tb_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 tb_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;
	//alert("width " + w + " height " + h);
	arrayPageSize = [w,h];
	return arrayPageSize;
}
 
function tb_detectMacXFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
	return true;
    }
}
 
$.fn.listHandlers = function(events, outputFunction) {
	return this.each(function(i){
		var elem = this,
		dEvents = $(this).data('events');
		if (!dEvents) {
			return;
		}
		$.each(dEvents, function(name, handler){
			if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
				$.each(handler, function(i,handler){
					outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
				});
			}
		});
	});
};

$(document).ready(function() { 
	//for bind
	jQuery(".thickbox_scroll").live("click", function() {
		var letterlink = jQuery(this).attr('href');
		var myURL= document.location.toString();
		if (myURL.match('#')) { // the URL contains an anchor
			myURL = myURL.split('#')[0]; }
			myURL = myURL + letterlink;
			window.location = myURL;
			return false;
	});
});


function tb_scrollTo(myURL) {
	if (myURL.match('#')) { // the URL contains an anchor
		var myAnchor = '#' + myURL.split('#')[1];
		myURL = document.location.toString();
		myURL = myURL.split('#')[0];
		window.location = myURL + myAnchor;
	}
}
