var refresh_on_colorbox_closed = false;

$(document).ready(function(){
	// Detect JS
	$("#jstest").load("/ajax/detectjs.php");

	//Datepicker
	$('.datepicker').each(function(){
		var args = new Object();
		var minDate = $(this).siblings('.minDate').val();
		if (minDate != null) {
			args.minDate = new Date(minDate);
		}
		var maxDate = $(this).siblings('.maxDate').val();
		if (maxDate != null) {
			args.maxDate = new Date(maxDate);
		}
		args.numberOfMonths = 2;
		$(this).datepicker(args);
	});
	$(".datepicker-icon").click(function () {
		var id = get_href_target(this);		
		$('#'+id).datepicker('show');
		return false;
	});
	
	//Colorbox Functionality
	$('.colorbox').each(function(){
		var vars = vars_from_string($(this).attr('name'));
		if (!vars.hasOwnProperty('innerWidth')) {
			vars.innerWidth = 650;
		}
		if (!vars.hasOwnProperty('innerHeight')) {
			vars.innerHeight = 500;
		}
		vars.onClosed = function(){
			if (refresh_on_colorbox_closed) {
				location.reload(true);
			}
		};
		if ($(this).colorbox) {			
			$(this).colorbox(vars);
		}
	});

	//Multiselect
	if( jQuery.fn.multiSelect || jQuery.multiSelect ) {
		$(".multiSelect").multiSelect({
			  selectAll: false,
			  oneOrMoreSelected: '*'
		});
	}

	//Colorbox picture select in bundles
	$('#propertypictureselect').find('a').click(function(){
		//Set the image
		var imageCopy = $(this).children('img').clone();
		$('#current_property_picture').children('img').remove();
		$('#current_property_picture').append(imageCopy);

		//Set the property id to the hidden input
		var href = $(this).attr('href');
		var pos = href.indexOf('#',href);
		var id = href.substr(pos+1);
		$('#property_picture_input').val(id);

		$('span#remove_controls').show();

		$.fn.colorbox.close();
		return false;
	});
	//Picture removal in bundles
	$('a#remove_property_picture').click(function(){
		$('#property_picture_input').val('0');
		$('#current_property_picture').children('img').remove();
		$(this).parents('span:first').hide();
		return false;
	});

	//Sortable
	if( jQuery.fn.sortable ) $('.sortable').sortable({axis:'y'});
	if( jQuery.fn.tableDnD ) {
		$('table.sortable-records').tableDnD({
			onDrop: function(table, row) {
			}
		});
	}


	//Show javascript elements that are hidden for non-js users
	var elementsToShow = $('body').find('.script-only');
	for (i=0; i<elementsToShow.length; i++) {
		elementsToShow[i].style.display = 'block';
	}
	var elementsToShow = $('body').find('.script-only-i');
	for (i=0; i<elementsToShow.length; i++) {
		elementsToShow[i].style.display = 'inline';
	}
	//Hide elements that don't need to be displayed for js-users
	var elementsToHide = $('body').find('.script-hide');
	for (i=0; i<elementsToHide.length; i++) {
		elementsToHide[i].style.display = 'none';
	}
	//Tab functionality
	$('ul.jt-tabs').each(function(){
		var tabVars = new Object();
		tabVars.initialIndex = $(this).children('li').index($(this).children('li.open:first'));
		if (tabVars.initialIndex == -1) {
			tabVars.initialIndex = 0;
		}
		tabVars.onClick = function(event, index){
			var clicked_tab = this.getTabs().eq(index);
			//Google maps placeholder functionality
			//Google maps can't load in a non-visible div. This is problematic within tabs, so we start with the map visible but positioned off-screen, then move it when they click the tab
			if ($(clicked_tab).hasClass('map-loader')) {				
				var map_id = $(clicked_tab).attr('href');				
				$(map_id).children().insertAfter(map_id+'-placeholder');
				$(map_id+'-placeholder').remove();
			}
		};

		$(this).tabs($(this).next('div.panes').children(), tabVars);		
	});

	$('#jsEnabled').val('true');
	$('.jsEnabled').val('true');

	$('div#main-itinerary').find('div.collapse').hide();

	//Fading notifications
	$('.auto-fade').each(function(){
		var obj = this;
		setTimeout(function(){
				$(obj).hide(1000);
			},
			2000
		);
	});

	$('.confirm').click(function() {
		$msg = $(this).attr('title');
		if ($msg.length == 0) {
			$msg = $(this).attr('name');
		}
		var response = confirm('Are you sure you want to '+$msg+'?');
		return response;
	});

	$('input.auto-select').focus(function() {
		$(this).select();
	});
	$('span.auto-select-inst').hide();

	//Compare checkbox functionality
	$('input.compare-checkbox').each(function(){
		$(this).qtip({
			content: 'Compare this with other properties'
		});
		$(this).change(function(){
			var cat = $(this).attr('name');
			var prop_id = $(this).val();
			if (this.checked) {
				var change_type = 'add_property';
			} else {
				var change_type = 'remove_property';
			}
			var change_url = '/compare/'+change_type+'/'+cat+'/'+prop_id;
			$.get(change_url);
		});
	});
	//Compare management links
	$('a.remove-compare').live('click', function(){
		var link = this;
		var url = $(this).attr('href');
		$.get(url, function(data){
			if (data == 'true') {
				$(link).parent().remove();
				refresh_on_colorbox_closed = true;
			}
		});

		return false;
	});

	//$('.time-show-list').tabs({ selected:3 });

	//Selects that instantly link to their value
	$('select.navigate').change(function(){
		window.location = $(this).val();									 
	});

	//Popup code
	$('a.new-window').bind('click',function(){ return false;});
	$('a.new-window').click(function(){
		var URL = $(this).attr('href');
		var wPos = URL.indexOf('w=');
		var hPos = URL.indexOf('h=');
		var width;
		var height;
		if (wPos != -1) {
		    width = URL.substr(wPos+2,4);
		} else {
		    width = 600;
		}
		if (hPos != -1) {
		    height = URL.substr(hPos+2,4);
		} else {
		    height = 600;
		}

		var parameters = 'height='+height+', width='+width+', scrollbars=yes, location=no, menubar=no';

		window.open(URL, 'Popup', parameters);
	});

	//Show/hide elements tied to checkbox statuses
	$('.toggle-box').click(function() {
		var name = $(this).attr('name');
		var partner = document.getElementById(name);
		if (this.checked == true) {
			$(partner).show();
		} else {
			$(partner).hide();
		}
	});
	$('.reverse-toggle-box').each(function(){
		var name = $(this).attr('name');
		var partner = $('#'+name);
		if (this.checked) {
			$(partner).hide();
		} else {
			$(partner).show();
		}
		$(this).click(function(){			
			if (this.checked) {				
				$(partner).hide();
			} else {
				$(partner).show();
			}
		});
	});

	$('#print-screen').bind("click", function() {return false;});
	$('#print-screen').click(function() {
		window.print();
	});

	//Functionality for elements that submit form when clicked / selected
	/*$('input:radio.instant-submit').each(function(){
		var id = $(this).attr('id');
		$(this).change(function(){
			alert('clicked');
		});
	});*/
	$('input:radio.instant-submit').each(function(){
		var radio = this;
		var id = $(this).attr('id');
		$(this).click(function(){
			setTimeout(function(){
				$(radio).parents('form:first').submit();
			}, 100);
		});
		$('label[for="'+id+'"]').click(function(){
			setTimeout(function(){
				$(radio).parents('form:first').submit();
			}, 100);
		});
	});

	//Colorbox picture select in bundles
	$('#propertypictureselect').find('a').click(function(){
		//Set the image
		var imageCopy = $(this).children('img').clone();
		$('#current_property_picture').children('img').remove();
		$('#current_property_picture').append(imageCopy);

		//Set the property id to the hidden input
		var href = $(this).attr('href');
		var pos = href.indexOf('#',href);
		var id = href.substr(pos+1);
		$('#property_picture_input').val(id);

		$('span#remove_controls').show();
		
		$.fn.colorbox.close();		
		return false;
	});
	//Picture removal in bundles
	$('a#remove_property_picture').click(function(){
		$('#property_picture_input').val('0');
		$('#current_property_picture').children('img').remove();
		$(this).parents('span:first').hide();
		return false;
	});

	//Hide/Show Flash
	if (document.getElementById('main-slideshow')) {
		var flash = $('#main-slideshow');
		var hideFlash = $('.flash-toggle')[0];
		var showFlash = $('.flash-toggle')[1];

		$(hideFlash).bind("click", function() {return false;});
		$(hideFlash).click(function() {
			$(flash).hide();
			$('#flash-shadow').show();
			$(hideFlash).hide();
			$(showFlash).show();
			var href = $(hideFlash).attr('href');
			var start = href.indexOf('#')+1;
			var key = href.substr(start);
			$.ajax({
				type: "GET",
				url: "/ajax/set-session.php?key="+key+"&val=hide"
			});
		});

		$(showFlash).bind("click", function() {return false;});
		$(showFlash).click(function() {
			$('#flash-shadow').hide();
			$(flash).show();
			$(showFlash).hide();
			$(hideFlash).show();
			var href = $(showFlash).attr('href');
			var start = href.indexOf('#')+1;
			var key = href.substr(start);
			$.ajax({
				type: "GET",
				url: "/ajax/set-session.php?key="+key+"&val=show"
			});
		});
	}

	var ajax = new Array();
	//Ajax search results keyboard navigation
	//$(document).bind("keydown", function(e) {if(e.keyCode == 40 || e.keyCode == 38) {return false;}});
	$('.ajax-input').keydown(function(e) {
		if (e.keyCode != 40 && e.keyCode != 38) {
			return;
		}
		var links = $(this).siblings('div').find('a');
		if (links.length == 0) {
			return;
		}
		var id = $(this).siblings('.ajax-results').attr('id');
		if (e.keyCode == 40) {
			if (ajax[id+'-link'] < (links.length-1)) {
				$(links[ajax[id+'-link']]).removeClass('hover');
				ajax[id+'-link']++;
			} else {
				return;
			}
			$(links[ajax[id+'-link']]).addClass('hover');
		}
		if (e.keyCode == 38) {
			if (ajax[id+'-link'] > 0) {
				$(links[ajax[id+'-link']]).removeClass('hover');
				ajax[id+'-link']--;
			} else {
				return;
			}
			$(links[ajax[id+'-link']]).addClass('hover');
		}
		switch (id) {
			case 'header-ajax-results':
				var url = links[ajax[id+'-link']].href;
				$(this).siblings('.directLink').val(url);
				break;
			case 'directions-ajax-results':
				var url = links[ajax[id+'-link']].href;
				var pos = url.indexOf('saddr=',url);
				var loc = url.substr(pos+6);
				$(this).siblings('input[name="ajax-saddr"]').val(loc);
		}
	});

	// Search Box AJAX
	//var headerSearchResults = $.ajax({type: "GET", url: "/search/ajax"});
	var headerSearchResults = null;
	var headerAjaxInput;
	if (document.getElementById('header-ajax-results')) {
		headerAjaxInput = $('#header-ajax-results').siblings('input.ajax-input');
		$(headerAjaxInput).keyup(function(e) {
			if (e.keyCode == 38 || e.keyCode == 40) {
				return;
			}
			headerRunAjax();
			ajax['header-ajax-results-link'] = -1;
		});

		var headerResultsFocus = false;
		$(headerAjaxInput).focus(function() {
			this.focused = this;
			headerResultsFocus = true;
			headerRunAjax();
			$('#header').css('z-index','3');
			$('.dateSelect').hide();
		});

		$(headerAjaxInput).blur(function() {
			resultsFocus = false;
			if (resultsHover == false) {
				$(headerAjaxInput).siblings('.directLink').val(false);
				headerHideResults();
			}
			$(headerAjaxInput).siblings('.directLink').val(false);
			setTimeout(headerHideResults,100);
		});
		var resultsHover = false;
		$('#header-ajax-results').mouseover(function() {
			resultsHover = true;
		});
		$('#header-ajax-results').mouseout(function() {
			resultsHover = false;
			if (headerResultsFocus == false) {
				headerHideResults();
			}
		});
	}
	function headerHideResults() {
		$('#header-ajax-results').html('');
		$('#header').css('z-index','1');
	}
	function headerRunAjax() {
		if (headerSearchResults != null) {
			headerSearchResults.abort();
		}
		var str = $(headerAjaxInput).val();
		str = str.replace('#','%23');
		if (str == '') {
			$('#header-ajax-results').html('');
		} else {
			headerSearchResults = $.ajax({
				type: "GET",
				url: "/search/ajax?search="+str,
				success: headerLoadAjax
			});
		}
	}
	function headerLoadAjax(html) {
		$('#header-ajax-results').html(html);
		$('#header-ajax-results').find('a').mousedown(function() {
			window.location.href = $(this).attr('href');
		});
	}

	//Driving directions AJAX
	var directionsAjaxInput;
	var directionsAjaxForm;
	//var directionsSearchResults = $.ajax({type: "GET", url: "/itinerary/ajax/directions"});
	var directionsSearchResults = null;
	if (document.getElementById('directions-ajax-results')) {
		directionsAjaxInput = $('#directions-ajax-results').siblings('input.ajax-input');
		directionsAjaxForm = $('#directions-ajax-results').parent();
		var directionsResultsFocus = false;
		$(directionsAjaxInput).focus(function() {
			directionsResultsFocus = true;
			directionsRunAjax();
			ajax['directions-ajax-results-link'] = -1;
		});
		$(directionsAjaxInput).blur(function() {
			resultsFocus = false;
			if (resultsHover == false) {
				$(directionsAjaxInput).siblings('.directLink').val(false);
				directionsHideResults();
			}
		});

		var resultsHover = false;
		$('#directions-ajax-results').mouseover(function() {
			resultsHover = true;
		});
		$('#directions-ajax-results').mouseout(function() {
			resultsHover = false;
			if (directionsResultsFocus == false) {
				directionsHideResults();
			}
		});
	}
	function directionsHideResults() {
		$('#directions-ajax-results').html('');
	}
	function directionsRunAjax() {
		var daddr = $(directionsAjaxInput).siblings('input[name="daddr"]').val();
		daddr = daddr.replace('#','%23');
		if (directionsSearchResults != null) {
			directionsSearchResults.abort();
		}
		directionsSearchResults = $.ajax({
			type: "GET",
			url: "/itinerary/ajax/directions?daddr="+daddr,
			success: directionsLoadAjax
		});
	}
	function directionsLoadAjax(html) {
		$('#directions-ajax-results').html(html);
		/*$('#directions-ajax-results').find('a').mousedown(function() {
			window.location.href = $(this).attr('href');
		});*/
	}
	$('.qTips a[href][title]').qtip({ content: { text: false 	}, show: { delay: 50 }, position: {	corner: { tooltip: 'bottomMiddle', target: 'topMiddle' } }, style: { border: { width: 5, radius: 10 }, padding: 10, textAlign: 'center', tip: true,	name: 'cream' }});
	$('.qTips input[title]').qtip({ content: { text: false 	}, show: { delay: 50 }, position: {	corner: { tooltip: 'bottomMiddle', target: 'topMiddle' } }, style: { border: { width: 5, radius: 10 }, padding: 10, textAlign: 'center', tip: true,	name: 'cream' }});
	$('img.qTips[title]').qtip({ content: { text: false 	}, show: { delay: 50 }, position: {	corner: { tooltip: 'bottomMiddle', target: 'topMiddle' } }, style: { border: { width: 5, radius: 10 }, padding: 10, textAlign: 'center', tip: true,	name: 'cream' }});
	$(".props").change(function(){
		resultID = 'perfs_'+$(this).attr('id');
		//alert(resultID);
		//alert("<?php echo site_url('/controlpanel/shows/get_performances/'.$this->uri->segment(4));?>/"+$('#'+$(this).attr('id')+' :selected').val());
		$.getJSON("<?php echo site_url('/controlpanel/shows/get_performances/'.$this->uri->segment(4));?>/"+$('#'+$(this).attr('id')+' :selected').val(), '', function(j){
			var toptions = '<option value=""> </option>';
			for (var i = 0; i < j.length; i++) {
				toptions += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
			}
			//alert(toptions);
			$('#'+resultID).html(toptions);
		});
	});
});

function vars_from_string(str) {
	var vars = new Object();
	var pairs = str.split('_');	
	if (pairs.length > 0) {
		for (var i=0; i < pairs.length; i++) {
			var pair = pairs[i].split(':');
			vars[pair[0]] = pair[1];
		}
	}
	return vars;
}

function get_href_target(link) {
	var href = $(link).attr('href');	
	var pos = href.indexOf('#',href);
	var id = href.substr(pos+1);
	return id;
}

