// AnythingSlider setup
function formatText(index, panel) {
  return index + " ";
}

jQuery(function ($) {
	$('#basic-modal input.basic, #basic-modal a.basic').click(function (e) {
		e.preventDefault();
		$('#basic-modal-content').modal({
			overlayClose:true
		});
	});
});

$(function () {
	$('.anythingSlider').anythingSlider({
		easing: "easeInOutExpo",        // Anything other than "linear" or "swing" requires the easing plugin
		autoPlay: false,
		delay: 3000,
		startStopped: false,
		animationTime: 600,
		hashTags: true,
		buildNavigation: false,
		pauseOnHover: true,
		startText: "Go",
		stopText: "Stop",
		forwardText: "Next",
		previousText: "Prev",
		navigationFormatter: formatText,
		hideNav: false
	});
	
	$('.objectTiles').anythingSlider({
		easing: "easeInOutExpo",        // Anything other than "linear" or "swing" requires the easing plugin
		autoPlay: false,
		delay: 3000,
		startStopped: false,
		animationTime: 600,
		hashTags: true,
		buildNavigation: true,
		pauseOnHover: true,
		startText: "Go",
		stopText: "Stop",
		forwardText: " Next",
		previousText: "Previous ",
		navigationFormatter: formatText,
		hideNav: true
	});
});
// end anything slider setup

$(document).ready(function()
{
	$(".seo_text").hide();
	
	$(".seo_text_show").click(function()
	{
		$('.seo_text').slideToggle(600);
		var x = $('body').attr("scrollHeight"); //insert your own formula to calculate where you want to scroll to in px
		var t = 500; //arbitrary time in ms
		$('body').animate({ scrollTop: x }, t);

	});
	
	// reg form tips
	$('.regTable input, .regTable select').focus(function(){
		$('.tooltip').hide();
		//$(this).next("span").fadeIn();
		$(this).next('span').fadeIn();
	});
	
	// accordion animation fix
	$(".ui-accordion-header").click(function() {
		$(this).next().fadeIn();
	});
	
	// game elements
	$('div.game-mid').mouseover(function(){
		$('.ply_now').hide();
		$('.ply_now_btn').hide();
		$("div.overlay_" + this.id).show();
		$("img.btn_" + this.id).show();
		
	});
	$('div.game-mid').mouseout(function(){
		$('.ply_now').hide();
		$('.ply_now_btn').hide();
	});
		
	$('#close_help').click(
		function () {
			$('#hlp_ctnt').hide();
			$('#non_hlp_ctnt').fadeIn();
		}
	);
		
	$('#log_in').click(
		function () {
			fn_ajaxLoad('pop_container', base_lang_url + 'ajax-pages/force-login', '433', '280');
		}
	);
	
	
	
	$(".validationFormLog").validate({
		errorClass: "display_error"
	});
	
	$('#regForm').validate({
		errorClass: "display_error",
		groups:
		{
			dob: 'birthMonth birthDay birthYear'
		},
		errorPlacement: function(error, element)
		{
			if (element.attr("name") == "birthDay" || element.attr("name") == "birthYear" )
			{
				error.insertAfter("#birthYear");
			}
			else if (element.attr("name") == "agreeterms")
			{
				error.insertAfter("#terms");
			}
			else if (element.attr("name") == "ageverify")
			{
				error.insertAfter("#age");
			}
			else
			{
				error.insertAfter(element);
			}  
		},
		invalidHandler: function(form, validator)
		{
			$('div.formSection').show();
			$('span.ui-icon').attr("class", "ui-icon ui-icon-triangle-1-s");
			$("#regForm h3.rowHeader a").unbind();
		}
	});
		
	$("#winners_tbl_slider_y").easySlider({
		controlsShow: false,		
		vertical: true,
		speed: 1400,
		auto: true,
		pause: 5000,
		continuous: true
	});

	$("#winners_tbl_slider").easySlider({
		prevText:  prev_link,
        nextText: next_link,
		vertical: true
	});

	$("table.report tr:even").addClass("even");
	$("table.report tr:odd").addClass("odd");

	$(".checkBoxTree").each(function(){          
		addTreeView($(this), "", "", false, false);
		$(this).TreeViewCheckboxes();              
		$(this).show();                            
	});
	
	$("select.sort").each(function() {
	    var selectedVal = $(this).val();
		$(this).sortOptions(true);
		$(this).val(selectedVal);
	});
	
	$("#country").change(function() {
		
		var countryVal = $(this).val();
	
		// check country ajax
		$.ajax({
			type: "POST",
			url: webRoot + "/auth/check_country_currency",
			data: {country:countryVal},
			success: function(response)
			{
				$("#currency").val(response);
			}
		});
	});
});

/* Registration form accordion */
$(function() {
	$("#regForm h3.rowHeader a").each(function()
	{ 
		$(this).before('<span class="ui-icon ui-icon-triangle-1-e"></span>');
		
		$(this).bind('click focus', function()
		{
			var section_number = $(this).parent().attr('id');
			section_number = section_number.replace("header-", "");
			
			$(".formSection").each(function()
			{
				//$(this).hide();
				$("h3.rowHeader span").attr("class", "ui-icon ui-icon-triangle-1-e");
			});
			
			var icon_span = $(this).parent().children('span.ui-icon');
			icon_span.attr("class", "ui-icon ui-icon-triangle-1-s");
			
			//$("#section-" + section_number).show();
		});
	});
	
	/*
	$("#regForm div.formSection").each(function()
	{
		$(this).hide();
	});
	
	$("#regForm div#section-1").show();
	*/
	$("#regForm h3#header-1 span").attr("class", "ui-icon ui-icon-triangle-1-s");
});


function initDataTables(localeFile) {
	$(".report").each(function() {
		if (!$(this).hasClass("notDynamic")) {
			$(this).dataTable({
				"bPaginate":true,
				"bLengthChange":false,
				"bFilter":false,
				"bSort":true,
				"bInfo":true,
				"bProcessing":true,
				"bAutoWidth":true,
				"iDisplayLength":25,
				"sPaginationType":"full_numbers",
				"oLanguage": {
					"sUrl": localeFile
				}
			});
		}
	});
}

function parseXML( xml ) {
	if( window.ActiveXObject && window.GetObject ) {
		var dom = new ActiveXObject( 'Microsoft.XMLDOM' );
		dom.loadXML( xml );
		return dom;
	}
	if( window.DOMParser ) {
		return new DOMParser().parseFromString( xml, 'text/xml' );
	}
	throw new Error( 'No XML parser available' );
} 

jQuery.parseXML = function( xml ) {
   	return jQuery( parseXML(xml) );
};

function addTreeView(element, animation, persist, collapsed, unique) {
	$(element).treeview({                                               
		animated: animation,                                              
		persist: persist,                                                 
		collapsed: collapsed,                                            
		unique: unique                                                    
	});                                                                 
}          

function checkAliasExists(alias)
{
	var alias = alias.value;
	
	$('.iconloader').show();
	
	$.ajax({
		type: "POST",
		url: webRoot + "auth/check_alias",
		data: {selectedAlias:alias},
		success: function(msg)
		{
			$(".aliasValidation").html(jQuery.trim(msg));
			$('.iconloader').hide();
		}
	});
}

// Setup the report datepickers
$(function() {
	$("#hiddenStartDate").datepicker({
		showOn: 'button',
		dateFormat: "m/d/yy",
		buttonImage: webRoot + 'themes/sexy_casino/assets/images/common/icons/calendar.jpg',
		buttonImageOnly: true,
		showAnim: "fadeIn",
		onSelect: function(dateText, inst) {
		
			// explode date
			var dateparts = dateText.split("/");

			// set date dropdowns
			$('#startMonth').val(dateparts[0]);
			$('#startDay').val(dateparts[1]);
			$('#startYear').val(dateparts[2]);
		}
	});
});

function jQuery_setFixedDate()
{
	var fixedVal = $('#fixedDate').val();
	
	if (fixedVal != 0)
	{
		var dt = new Date();
		var timestamp = dt.getTime() - fixedVal * 24 * 60 * 60 * 1000;
		
		var newDate = new Date(timestamp);
	
		// Set the date fields
		$('#startMonth').val(newDate.getMonth() + 1);
		$('#startDay').val(newDate.getDate());
		$('#startYear').val(newDate.getFullYear());
	}
}

$(function() {
	$("#hiddenEndDate").datepicker({
		showOn: 'button',
		dateFormat: "m/d/yy",
		buttonImage: webRoot + 'themes/sexy_casino/assets/images/common/icons/calendar.jpg',
		buttonImageOnly: true,
		showAnim: "fadeIn",
		onSelect: function(dateText, inst) {
		
			// explode date
			var dateparts = dateText.split("/");

			// set date dropdowns
			$('#endMonth').val(dateparts[0]);
			$('#endDay').val(dateparts[1]);
			$('#endYear').val(dateparts[2]);
		}
	});
});

function fn_ajaxLoad(container, url, boxWidth, boxHeight)
{
	// Default container: #simplemodal-container - 400/711
	
	if (boxWidth == null)
	{
		boxWidth = '840px';
	}
	if (boxHeight == null)
	{
		boxHeight = '500';
	}
	
	$('#basic-modal-content').modal({
		minHeight:boxHeight,
		minWidth: boxWidth
	});
	
	$('#' + container).html();
	$('#' + container).load(url);
}

// menu functionality
function fn_ajaxLoadSwap_open_help(url)
{	
	$('#content_wrapper_ajax').load(url, function() {
	
		$('#content_wrapper').hide();
		$('#content_wrapper_ajax').fadeIn();
		
		// show/hide menus
		$('#non_hlp_ctnt').hide();
		$('#account_ctnt').hide();
		$('#hlp_ctnt').fadeIn();
	
	});
}

function fn_showHide_open_act(url)
{	
	$('#content_wrapper_ajax').load(url, function() {
		
		$('#content_wrapper').hide();
		$('#content_wrapper_ajax').fadeIn();
		
		// show/hide menus
		$('#non_hlp_ctnt').hide();
		$('#hlp_ctnt').hide();
		$('#account_ctnt').fadeIn();

	});
}

function fn_showHide_toggle_menu()
{
	$('#account_ctnt').hide();
	$('#hlp_ctnt').hide();
	$('#content_wrapper_ajax').hide();
	
	$('#content_wrapper').show();
	$('#non_hlp_ctnt').show();
}

function confirm(message, callback) {
	$('#confirm').modal({
		closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
		position: ["20%",],
		overlayId: 'confirm-overlay',
		containerId: 'confirm-container', 
		onShow: function (dialog) {
			$('.message', dialog.data[0]).append(message);

			// if the user clicks "yes"
			$('.yes', dialog.data[0]).click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				$.modal.close();
			});
		}
	});
}

function fn_pop_freeCasino(configid, gametype)
{
	var theForm = gametype + configid;
	
	$('#' + theForm).ajaxSubmit({
				
		success: function(responseXML) {
			
			$('#launch-form').html(responseXML);
			
			$('#Game' + configid).attr('target', 'launch_frame');
			$('#Game' + configid).submit();
		}
	});
}

function fn_autoLogGame()
{
	// open the window and hide
	var gamePopWin = window.open("", "gamePopWin","menubar=0,resizable=0,width=20,height=20");
	gamePopWin.blur();
	
	$('#gameLoginForm').ajaxSubmit({
				
		success: function(response) {
			
			if (response.indexOf('true') != -1) {			
				// edit new window
				gamePopWin.resizeTo(760, 570);
				gamePopWin.focus();
				
				// submit the game launch form
				$('#current_game').submit();
				
				// reload parent window
				window.location.reload(true);
				
				if (navigator.userAgent.indexOf("MSIE") == -1) {
					// edit parent window
					window.blur();
				}
			} else {			
				gamePopWin.close();
				$('.errortext').html(response);
			}
		}
	});
}

function fn_autoLogMessage()
{
	$('#popupLoginForm').ajaxSubmit(
	{
		success: function(response) 
		{
			// reload parent window
			var current_page  = window.location;
			window.location = current_page + '?message-me=true';
		}	
	});
}

function fn_submitAjaxRequest(theForm, responseCont)
{
	$('#' + theForm).ajaxSubmit({
				
		success: function(responseXML) {
			
			// post ecom redirect form
			$('#' + responseCont).html(responseXML);

		}
	});
}

jQuery.fn.uncheck = function() {
   return this.each(function() {
     this.checked = false;
   });
};

jQuery.fn.check = function() {
   return this.each(function() {
     this.checked = true;
   });
};

jQuery.fn.TreeViewCheckboxesOff = function() {
	$(this).each(function() {
		$(this).parent().find(":checkbox").uncheck();
		$(this).removeClass("checkbox-checked").addClass("checkbox-unchecked").removeClass("checkbox-partial");
	});
};

jQuery.fn.TreeViewCheckboxesOn = function() {
	$(this).each(function() {
		$(this).parent().find(":checkbox").check();
		$(this).addClass("checkbox-checked").removeClass("checkbox-unchecked").removeClass("checkbox-partial");
	});
};

jQuery.fn.TreeViewCheckboxesToggle = function(){
	var check = $(":checkbox[id='"+this.attr("for")+"']")[0];
	var wasChecked = check.checked;

	var parentListItem = this.parent();
	var parentNodes = parentListItem.parents().filter(".expandable, .collapsable");
	var hasChildren = $(parentListItem).hasClass("expandable") || $(parentListItem).hasClass("collapsable");

	if (hasChildren) {
		// An expandable node was clicked.  We have to either check/uncheck all children below.
		var childItems = $(parentListItem).find("li label");
		if (wasChecked) {
			$(childItems).TreeViewCheckboxesOff();
			this.addClass("checkbox-checked").removeClass("checkbox-unchecked").removeClass("checkbox-partial");
		} else {
			$(childItems).TreeViewCheckboxesOn();
			this.removeClass("checkbox-checked").addClass("checkbox-unchecked").removeClass("checkbox-partial");
		}
	}

	// Now, traverse up the tree to update any higher-level checkboxes
	if (parentNodes.length > 0) {
		$(parentNodes).each(function(){
			var label = $(this).children("label");
			var allChildrenSize = $(this).find("li :checkbox").length;
			var checkedChildrenSize = $(this).find("li :checkbox:checked").length;

			if (wasChecked) {
				checkedChildrenSize -= 1;
			} else {
				checkedChildrenSize += 1;
			}

			var theCheckBox = $(":checkbox[id='"+$(label).attr("for")+"']"); 
			if (allChildrenSize != checkedChildrenSize && checkedChildrenSize == 0) {
				$(label).removeClass("checkbox-partial").removeClass("checkbox-checked").addClass("checkbox-unchecked");
				theCheckBox.uncheck();
			} else if (allChildrenSize != checkedChildrenSize) {
				$(label).addClass("checkbox-partial").removeClass("checkbox-checked").removeClass("checkbox-unchecked");
				theCheckBox.uncheck();
			} else {
				$(label).addClass("checkbox-checked").removeClass("checkbox-unchecked").removeClass("checkbox-partial");
				theCheckBox.check();
			}
		});
	}

	// Click the hidden input box for IE only.  Firefox will cascade the click down.
	if ($.browser.msie) {
		check.click();
	}

	this.toggleClass("checkbox-checked").toggleClass("checkbox-unchecked");
}

jQuery.fn.TreeViewCheckboxes = function(){
	$(":checkbox", this)
	// Hide native checkboxes
	.hide()
	// Find related labels and add the styles
	.each(function(){
		var check = this;
		var jlabel = $("label[for='"+$(check).attr("id")+"']");
		var disabled = $(check).attr("disabled");

		// Initial state check
		if (check.checked) {
			if (!check.disabled) {
				jlabel.addClass("checkbox-checked");
			} else {
				jlabel.addClass("checkbox-checked-disabled");
			}
		} else {
			if (!check.disabled) {
				jlabel.addClass("checkbox-unchecked");
			} else {
				jlabel.addClass("checkbox-unchecked-disabled");
			}
		}

		jlabel.hover(
			function() { $(this).addClass("over"); },
			function() { $(this).removeClass("over"); }
		)

		// Label click state
		jlabel.click(function(){
			var check = $(":checkbox[id='"+$(this).attr("for")+"']")[0];
			if ($(check).attr("disabled") != true) {
				$(this).TreeViewCheckboxesToggle();
			}
		});
	});
	var treeNodes = $(this).find("li:first").markInputs();
}

jQuery.fn.markInputs = function() {
	var treeNodes = $(this).find("li.expandable, li.collapsable").andSelf();
	treeNodes.each(function() {
		$(this).markInput();
	});
};

jQuery.fn.markInput = function() {
	var label = $(this).children("label");
	var check = $(this).children(":checkbox");
	var allChildrenSize = $(this).find("li :checkbox").length;
	var checkedChildrenSize = $(this).find("li :checkbox:checked").length;
	
	if (allChildrenSize != checkedChildrenSize && checkedChildrenSize == 0) {
		if ($(check).attr("disabled") != true) {
			$(label).removeClass("checkbox-partial").removeClass("checkbox-checked").addClass("checkbox-unchecked");
		} else {
			$(label).removeClass("checkbox-partial-disabled").removeClass("checkbox-checked-disabled").addClass("checkbox-unchecked-disabled");
		}
		$(check).uncheck();
	} else if (allChildrenSize != checkedChildrenSize) {
		if ($(check).attr("disabled") != true) {
			$(label).addClass("checkbox-partial").removeClass("checkbox-checked").removeClass("checkbox-unchecked");
		} else {
			$(label).addClass("checkbox-partial-disabled").removeClass("checkbox-checked-disabled").removeClass("checkbox-unchecked-disabled");
		}
		$(check).uncheck();
	} else {
		if ($(check).attr("disabled") != true) {
			$(label).addClass("checkbox-checked").removeClass("checkbox-unchecked").removeClass("checkbox-partial");
		} else {
			$(label).addClass("checkbox-checked-disabled").removeClass("checkbox-unchecked-disabled").removeClass("checkbox-partial-disabled");
		}
		$(check).check();
	}
};
