/*
 * This file is part of a larger software package. Please read the License file 
 * in the root of this installation for terms of usage and distribution.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * 
 * CORE: manage/assets/scripts/demo.js - version 1.02
*/

// Widget for autocomplete search
$.widget( "custom.catcomplete", $.ui.autocomplete, {
	_renderMenu: function( ul, items ) {
		var self = this,
			currentCategory = "";
		$.each( items, function( index, item ) {
			if ( item.category != currentCategory ) {
				ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
				currentCategory = item.category;
			}
			self._renderItem( ul, item );
		});
	}
});

// Initialize ajax loader images
var loaderImgL = "<div id=\"loader\"><img src='assets/images/loading.gif' width='42' height='42' alt='Loading...' /></div>";
var loaderImgS = "<div id=\"loader\"><img src='assets/images/loading_s.gif' width='15' height='15' alt='Saving...' /></div>";

// Handle notifications on pages (div with id 'notify' required)
function showNotify(xText,xType){
	if(!xText || !$('#notify')){ return; }
	if($("#notify").is(":hidden")) {
		$('#notify').removeClass().addClass('notification '+xType);
		$('#notify').html(xText);
		$("#notify").slideDown();
	} else {
		$("#notify").slideUp(function(){
			$('#notify').removeClass().addClass('notification '+xType);
			$('#notify').html(xText);
			$("#notify").slideDown();
		});
	}
	setTimeout('$("#notify").slideUp("slow")', 8000); // hide after 8 seconds
}

function showEventNotify(xText,xType){
	if(!xText || !$('#eventnotify')){ return; }
	if($("#eventnotify").is(":hidden")) {
		$('#eventnotify').removeClass().addClass('notification '+xType);
		$('#eventnotify').html(xText);
		$("#eventnotify").slideDown();
	} else {
		$("#eventnotify").slideUp(function(){
			$('#eventnotify').removeClass().addClass('notification '+xType);
			$('#eventnotify').html(xText);
			$("#eventnotify").slideDown();
		});
	}
	setTimeout('$("#eventnotify").slideUp("slow")', 5000); // hide after 5 seconds
}

// Handle jumps from dropdowns
function gotoHref(theSelect) {
	if(theSelect.value != "") {
		thehref = theSelect.options[theSelect.selectedIndex].value;
		window.location.href = thehref;
	}
}

// tooltip and guide helpers
function showGuide(){
	$("[rel=guide]").each(function(){
		$(this).twipsy('show');
		window.setTimeout( hideGuide , 7000, true);
	})
}
function hideGuide(){
	$("[rel=guide]").each(function(){
		$(this).twipsy('hide');
	})
}
function hideTooltips(){
	$("[rel=tooltips]").each(function(){
		$(this).twipsy('hide');
	})
}

var activeDialog = "";
var activeDeleteDialog = "";

// View/edit dialog
openEditDialog = function(xType,xItemID,xTitle){
	var loadURL = "";
	var dialogH = 480;
	var dialogW = 640;
	switch(xType){
		case "event":
			loadURL = "dialog/event_modify.php?eid="+xItemID;
			dialogH = 300; dialogW = 800;
			break;
		case "tournament":
			loadURL = "dialog/tournament_modify.php?tid="+xItemID;
			dialogH = 560; dialogW = 800;
			break;
		case "series":
			loadURL = "dialog/series_modify.php?tsid="+xItemID;
			dialogH = 560; dialogW = 800;
			break;
		case "tournamentToArchive":
			loadURL = "dialog/tournament_modify.php?tid="+xItemID+"#tab-3";
			dialogH = 560; dialogW = 800;
			break;
		case "team":
			loadURL = "dialog/team_modify.php?team="+xItemID;
			dialogH = 480; dialogW = 800;
			break;
		case "tournamentteam":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/team_modify.php?team="+xItemARRAY[0]+"&tid="+xItemARRAY[1];
			dialogH = 480; dialogW = 800;
			break;
		case "seriesteam":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/team_modify.php?team="+xItemARRAY[0]+"&tsid="+xItemARRAY[1];
			dialogH = 480; dialogW = 800;
			break;
		case "sponsor":
			loadURL = "dialog/sponsor_modify.php?sponsor="+xItemID;
			dialogH = 480; dialogW = 800;
			break;
		case "tournamentsponsor":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/sponsor_modify.php?sponsor="+xItemARRAY[0]+"&tid="+xItemARRAY[1];
			dialogH = 480; dialogW = 800;
			break;
		case "seriessponsor":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/sponsor_modify.php?sponsor="+xItemARRAY[0]+"&tsid="+xItemARRAY[1];
			dialogH = 480; dialogW = 800;
			break;
		case "tournamentseries":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/tournament_modify.php?tid="+xItemARRAY[0]+"&tsid="+xItemARRAY[1];
			dialogH = 560; dialogW = 800;
			break;
		case "species":
			loadURL = "dialog/species_modify.php?species="+xItemID;
			dialogH = 560; dialogW = 800;
			break;
		case "tournamentspecies":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/species_modify.php?species="+xItemARRAY[0]+"&tid="+xItemARRAY[1];
			dialogH = 560; dialogW = 800;
			break;
		case "boat":
			loadURL = "dialog/boat_modify.php?boat="+xItemID;
			dialogH = 480; dialogW = 800;
			break;
		case "angler":
			loadURL = "dialog/angler_modify.php?angler="+xItemID;
			dialogH = 500; dialogW = 800;
			break;
		case "prod":
			loadURL = "dialog/prod_modify.php?prod="+xItemID;
			dialogH = 560; dialogW = 900;
			break;
		case "cat":
			loadURL = "dialog/category_modify.php?cat="+xItemID;
			dialogH = 560; dialogW = 800;
			break;
		case "cust":
			loadURL = "dialog/cust_modify.php?cust="+xItemID;
			dialogH = 560; dialogW = 800;
			break;
		case "custtype":
			loadURL = "dialog/custtype_modify.php?custtype="+xItemID;
			dialogH = 420; dialogW = 800;
			break;
		case "prodtag":
			loadURL = "dialog/prodtag_modify.php?prodtag="+xItemID;
			dialogH = 560; dialogW = 800;
			break;
		case "disc":
			loadURL = "dialog/disc_modify.php?disc="+xItemID;
			dialogH = 460; dialogW = 900;
			break;
		case "usr":
			loadURL = "dialog/user_add.php?usr="+xItemID;
			dialogH = 420; dialogW = 640;
			break;
	}
	// load remote content
	var dialogDiv = '<div style="display:hidden;" id="dialogDiv"></div>';
	var dialog = $(dialogDiv).appendTo('body');
    activeDialog = dialog.load(
        loadURL, 
        {},
        function (responseText, textStatus, XMLHttpRequest) {
			dialog.dialog({
				title: xTitle,
				resizable: true, autoOpen: true, modal: true,
				height: dialogH, width: dialogW,
				open: function(){
					$(this).scrollTop(0);
					$("[rel=tooltips]").twipsy({ "placement":"right", "offset":5, "html":true }); // initialize tooltips
					$("[rel=guide]").twipsy({ "placement":"left", "offset":5, "html":true, "trigger":"manual" }); // initialize tooltip guide
				},
				close: function(event, ui) {
					$(this).dialog("destroy").remove();
					activeDialog = "";
					if(xType=="event"){ try{ nLoadEventModify(); }catch(e){} }
				}
			});
        }
    );
}

// Delete dialog
openDeleteDialog = function(xType,xItemID,xTitle){
	var loadURL = "";
	var dialogH = 204;
	var dialogW = 540;
	switch(xType){
		case "tournamentspecies":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/tournament_species_delete.php?spid="+xItemARRAY[0]+"&tid="+xItemARRAY[1]; dialogW = 600;
			break;
		case "tournamentsponsor":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/tournament_sponsor_delete.php?sid="+xItemARRAY[0]+"&tid="+xItemARRAY[1]; dialogW = 600;
			break;
		case "tournamentteam":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/tournament_team_delete.php?teamid="+xItemARRAY[0]+"&tid="+xItemARRAY[1]; dialogW = 600;
			break;
		case "tournamentteamangler":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/tournament_team_angler_delete.php?aid="+xItemARRAY[0]+"&teamid="+xItemARRAY[1]+"&tid="+xItemARRAY[2]; dialogW = 600;
			break;
		case "seriessponsor":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/series_sponsor_delete.php?sid="+xItemARRAY[0]+"&tsid="+xItemARRAY[1]; dialogW = 600;
			break;
		case "seriestournament":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/series_tournament_delete.php?tid="+xItemARRAY[0]+"&tsid="+xItemARRAY[1]; dialogW = 600;
			break;
		case "seriesteam":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/series_team_delete.php?teamid="+xItemARRAY[0]+"&tsid="+xItemARRAY[1]; dialogW = 600;
			break;
		case "seriesteamangler":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/series_team_angler_delete.php?aid="+xItemARRAY[0]+"&teamid="+xItemARRAY[1]+"&tsid="+xItemARRAY[2]; dialogW = 600;
			break;
		case "teamangler":
			var xItemARRAY = xItemID.split(":");
			loadURL = "dialog/team_angler_delete.php?aid="+xItemARRAY[0]+"&teamid="+xItemARRAY[1]; dialogW = 600;
			break;
		case "event": loadURL = "dialog/event_delete.php?id="+xItemID; dialogW = 600; break;
		case "tournament": loadURL = "dialog/tournament_delete.php?id="+xItemID; dialogW = 600; break;
		case "tournamentArchive": loadURL = "dialog/tournament_archive.php?id="+xItemID; dialogW = 600; break;
		case "series": loadURL = "dialog/series_delete.php?id="+xItemID; dialogW = 600; break;
		case "seriesArchive": loadURL = "dialog/series_archive.php?id="+xItemID; dialogW = 600; break;
		case "team": loadURL = "dialog/team_delete.php?id="+xItemID; dialogW = 600; break;
		case "sponsor": loadURL = "dialog/sponsor_delete.php?id="+xItemID; dialogW = 600; break;
		case "species": loadURL = "dialog/species_delete.php?id="+xItemID; dialogW = 600; break;
		case "boat": loadURL = "dialog/boat_delete.php?id="+xItemID; dialogW = 600; break;
		case "angler": loadURL = "dialog/angler_delete.php?id="+xItemID; dialogW = 600; break;
		case "cat": loadURL = "dialog/category_delete.php?id="+xItemID; dialogW = 600; break;
		case "custtype": loadURL = "dialog/custtype_delete.php?id="+xItemID; dialogW = 600; break;
		case "order": loadURL = "dialog/order_delete.php?id="+xItemID; break;
		case "cust": loadURL = "dialog/cust_delete.php?id="+xItemID; break;
		case "prodtag": loadURL = "dialog/prodtag_delete.php?id="+xItemID; dialogW = 600; break;
		case "disc": loadURL = "dialog/discount_delete.php?id="+xItemID; break;
		case "usr": loadURL = "dialog/user_delete.php?id="+xItemID; break;
		case "plugin": loadURL = "dialog/plugin_delete.php?id="+xItemID; break;
	}
	// load remote content
	var dialogDiv = '<div style="display:hidden;" id="dialogDiv"></div>';
	var dialog = $(dialogDiv).appendTo('body');
    activeDeleteDialog = dialog.load(
        loadURL, 
        {},
        function (responseText, textStatus, XMLHttpRequest) {
			dialog.dialog({
				title: xTitle,
				resizable: false, autoOpen: true, modal: true,
				height: dialogH, width: dialogW,
				open: function(){
					$(this).scrollTop(0);
					$("[rel=tooltips]").twipsy({ "placement":"right", "offset":5 }); // initialize tooltips
					$("[rel=guide]").twipsy({ "placement":"left", "offset":5, "html":true, "trigger":"manual" }); // initialize tooltip guide
				},
				close: function(event, ui) {
					$(this).dialog("destroy").remove();
					activeDeleteDialog = "";
				}
			});
        }
    );
}

// Multiple edit dialog
editList = function(xType,xAction){
	if(!$("#nListForm")){ return; }
	var formData = $("#nListForm").serialize();
	var params = "";
	var loadURL = "";
	var dialogH = 300;
	var dialogW = 550;
	var xTitle = "";
	switch(xType){
		case "prod":
			if(xAction=="remove"){ params = "nPageID=prod&nRemove=1"; xTitle = "Remove Products"; }
			if(xAction=="edit"){ params = "nPageID=prod&nEdit=1"; xTitle = "Edit Products"; }
			break;
		case "ord":
			if(xAction=="remove"){ params = "nPageID=order&nRemove=1"; xTitle = "Remove Orders"; }
			if(xAction=="edit"){ params = "nPageID=order&nEdit=1"; xTitle = "Edit Orders"; }
			break;
		case "cust":
			if(xAction=="remove"){ params = "nPageID=cust&nRemove=1"; xTitle = "Remove Customers"; }
			if(xAction=="edit"){ params = "nPageID=cust&nEdit=1"; xTitle = "Edit Customers"; }
			break;
		case "custtype":
			if(xAction=="remove"){ params = "nPageID=custtype&nRemove=1"; xTitle = "Remove Customer Types"; }
			if(xAction=="edit"){ params = "nPageID=custtype&nEdit=1"; xTitle = "Edit Customer Types"; }
			break;
		case "disc":
			if(xAction=="remove"){ params = "nPageID=disc&nRemove=1"; xTitle = "Remove Discounts"; }
			if(xAction=="edit"){ params = "nPageID=disc&nEdit=1"; xTitle = "Edit Discounts"; }
			break;
		case "usr":
			if(xAction=="remove"){ params = "nPageID=usr&nRemove=1"; xTitle = "Remove Users"; }
			if(xAction=="edit"){ params = "nPageID=usr&nEdit=1"; xTitle = "Edit Users"; }
			break;
	}
	if(formData){ params+="&"+formData; }
	// load remote content
	var dialogDiv = '<div style="display:hidden;" id="dialogDiv"></div>';
	var dialog = $(dialogDiv).appendTo('body');
      activeDialog = dialog.load(
          "dialog/multiple_edit.php?"+params, 
          {},
          function (responseText, textStatus, XMLHttpRequest) {
			dialog.dialog({
				title: xTitle,
				resizable: true, autoOpen: true, modal: true,
				height: dialogH, width: dialogW,
				close: function(event, ui) {
					$(this).dialog("destroy").remove();
					activeDialog = "";
				}
			});
          }
      );
}

dialogClose = function(){
	if( activeDialog.dialog("close") ){ activeDialog = ""; }
}
dialogDeleteClose = function(){
	if( activeDeleteDialog.dialog("close") ){ activeDeleteDialog = ""; }
}

// Force POST processing on load function with JQuery
$.fn.serializeObject = function() {
	var arrayData, objectData;
	arrayData = this.serializeArray();
	objectData = {};
	$.each(arrayData, function() {
		var value;
		if (this.value != null) {
			value = this.value;
		} else {
			value = '';
		}
		if (objectData[this.name] != null) {
			if (!objectData[this.name].push) {
				objectData[this.name] = [objectData[this.name]];
			}
			objectData[this.name].push(value);
		} else {
			objectData[this.name] = value;
		}
	});
	
	return objectData;
};

// Chart helpers
function weekendAreas(axes) {
	var markings = [];
	var d = new Date(axes.xaxis.min);
	// go to the first Saturday
	d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
	d.setUTCSeconds(0);
	d.setUTCMinutes(0);
	d.setUTCHours(0);
	var i = d.getTime();
	do {
		// when we don't set yaxis, the rectangle automatically
		// extends to infinity upwards and downwards
		markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
		i += 7 * 24 * 60 * 60 * 1000;
	} while (i < axes.xaxis.max);
	return markings;
}

$(function(){
	// setup button icons
	$('.icon').each(function () {
		$(this).button({
			icons : {
				primary : $(this).attr('data-icon-primary') ? $(this).attr('data-icon-primary') : null, 
				secondary : $(this).attr('data-icon-primary') ? $(this).attr('data-icon-secondary') : null
			}, 
			text : $(this).attr('data-icon-only') === 'true' ? false : true
		});
	});
	
	// setup the view switcher
	$('.view-switcher > h2 > a').click(function(){
	    $(this).focus().parent().next().fadeIn();
	    return false;
	}).blur(function(){
	    $(this).parent().next().fadeOut();
	    return false;
	});
	function showTooltip(x, y, contents) {
		$('<div id="tooltip">' + contents + '</div>').css( {
			position: 'absolute',
			display: 'none',
			top: y - 5,
			left: x + 25,
			border: '1px solid #fdd',
			padding: '5px',
			'background-color': '#fee',
			opacity: 0.95
		}).appendTo("body").fadeIn(200);
	}
	var previousPoint = null;
	$(".chartHover").bind("plothover", function (event, pos, item) {
	    $("#x").text(pos.x.toFixed(2));
	    $("#y").text(pos.y.toFixed(2));
	    if(item){
	        if (previousPoint != item.dataIndex) {
	            previousPoint = item.dataIndex;
	            $("#tooltip").remove();
	            var x = item.datapoint[0].toFixed(2),
	                y = item.datapoint[1].toFixed(2);
				// check if currency
				var regex  = /[1-9]\d*(?:\.\d{2})?/;
				if(regex.test(y)){ delim = ": $"; } else { delim = ": "; }
	            showTooltip(item.pageX, item.pageY,
	                        item.series.label + delim + y);
	        }
	    } else {
	        $("#tooltip").remove();
	        previousPoint = null;            
	    }
	});
});

$(function() {

    // Autocomplete
    var countryList = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Comoros", "Congo, Democratic Republic", "Congo, Republic of the", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Fiji", "Finland", "France", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Greenland", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Mongolia", "Morocco", "Monaco", "Mozambique", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Oman", "Pakistan", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "Samoa", "San Marino", " Sao Tome", "Saudi Arabia", "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe"];
    $("#countries").autocomplete({
        source: countryList
    });

    // Accordion
    $(".accordion").accordion({ header: "h3" });

	/* Uploadify
	$('#file_upload').uploadify({
		'uploader'  : 'assets/scripts/uploadify/uploadify.swf',
		'script'    : 'assets/scripts/uploadify/uploadify.php',
		'cancelImg' : 'assets/scripts/uploadify/cancel.png',
		'folder'    : '../usr/img/tmp',
		'multi'     : true,
		'auto'      : true,
		'checkScript' : 'assets/scripts/uploadify/check.php',
		'onComplete' : function(event, ID, fileObj, response, data) {
			// response is the filename
			alert('The file ' + fileObj.name + ' was successfully uploaded with a response of ' + response + ':' + data);
		}
	});*/

    // Tabs
    $('.tabs').tabs();
    

    // Dialog			
    $('#dialog').dialog({
        autoOpen: false,
        width: 600,
        buttons: {
            "Ok": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        },
        modal: true
    });

    // Dialog Link
    $('#dialog_link').button().click(function() {
        $('#dialog').dialog('open');
        return false;
    });

    // Datepicker
    $('#datepicker').datepicker().children().show();

    // Horizontal Slider
    $('#horizSlider').slider({
        range: true,
        values: [17, 67]
    })

    // Vertical Slider				
    $("#eq > span").each(function() {
        var value = parseInt($(this).text());
        $(this).empty().slider({
            value: value,
            range: "min",
            animate: true,
            orientation: "vertical"
        });
    });

    //hover states on the static widgets
    $('#dialog_link, ul#icons li').hover(
        function() {
            $(this).addClass('ui-state-hover');
        },
        function() {
            $(this).removeClass('ui-state-hover');
        }
    );

    // Button
    $("#divButton, #linkButton, #submitButton, #inputButton").button();

    // Icon Buttons
    $("#leftIconButton").button({
        icons: {
            primary: 'ui-icon-wrench'
        }
    });

    $("#bothIconButton").button({
        icons: {
            primary: 'ui-icon-wrench',
            secondary: 'ui-icon-triangle-1-s'
        }
    });

    // Button Set
    $("#radio1").buttonset();


    // Progressbar
    $("#progressbar").progressbar({
        value: 37
    }).width(500);
    $("#animateProgress").click(function(event) {
        var randNum = Math.random() * 90;
        $("#progressbar div").animate({ width: randNum + "%" });
        event.preventDefault();
    });

    //Tooltips
	if( $('[rel=tooltips]').length != 0 ){
		$("[rel=tooltips]").twipsy({
		    "placement": "right",
		    "offset": 5
		});
	}
	if( $('[rel=guide]').length != 0 ){
		$("[rel=guide]").twipsy({ "placement":"left", "offset":5, "html":true, "trigger":"manual" }); // initialize tooltip guide
	}
	
	window.setTimeout(showGuide,1000,true); // show tutorial guides after 2 seconds
	$("[rel=guide]").click(function(){ hideGuide(); });

    //WYSIWYG Editor
    $(".cleditor").cleditor();

    //HTML5 Placeholder for lesser browsers. Uses jquery.placeholder.1.2.min.shrink.js
    $.Placeholder.init();


    //Uses formvalidator
    $("#form0, #form1, #form2").validationEngine();

    //Calendar
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        theme: true,
        defaultView: 'agendaWeek',
        events: [
            {
                title: 'All Day Event',
                start: new Date(y, m, 1)
            },
            {
                title: 'Long Event',
                start: new Date(y, m, d - 5),
                end: new Date(y, m, d - 2)
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: new Date(y, m, d - 3, 16, 0),
                allDay: false
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: new Date(y, m, d + 4, 16, 0),
                allDay: false
            },
            {
                title: 'Meeting',
                start: new Date(y, m, d, 10, 30),
                allDay: false
            },
            {
                title: 'Lunch',
                start: new Date(y, m, d, 12, 0),
                end: new Date(y, m, d, 14, 0),
                allDay: false
            },
            {
                title: 'Birthday Party',
                start: new Date(y, m, d + 1, 19, 0),
                end: new Date(y, m, d + 1, 22, 30),
                allDay: false
            },
            {
                title: 'Click for Google',
                start: new Date(y, m, 28),
                end: new Date(y, m, 29),
                url: 'http://google.com/'
            }
        ]
    });

    $('#gcalendar').fullCalendar({
        // US Holidays
        events: 'http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic',
        theme: true,

        eventClick: function(event) {
            // opens events in a popup window
            window.open(event.url, 'gcalevent', 'width=700,height=600');
            return false;
        },

        loading: function(bool) {
            if (bool) {
                $('#loading').show();
            } else {
                $('#loading').hide();
            }
        }
    });

});
























// Customize


$(function() {
    
    // Sliding Panel
    $(".trigger").click(function() {
        $(".panel").toggle("slow");
        $(this).toggleClass("active");
        return false;
    });

    // Color Picker for Demo

    $('#in-header').ColorPicker({
        color: '3d0707',
        onShow: function (colpkr) {
            
            $(colpkr).fadeIn(500);
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).fadeOut(500);
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            $('header').css('backgroundColor', '#' + hex);
            $('#in-header').css('backgroundColor', '#' + hex);
            $('#faux_header').css('backgroundColor', '#' + hex);
            createCookie('headerCss', hex);
        }
    });

    // Cookies for Demo

    $('#in-nav').ColorPicker({
        color: '222936',
        onShow: function (colpkr) {
            $(colpkr).fadeIn(500);
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).fadeOut(500);
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            $('nav, nav li, .sf-menu li li, .sf-menu li li li, #sidebar').css('backgroundColor', '#' + hex);
            $('#in-nav').css('backgroundColor', '#' + hex);
            createCookie('navCss', hex);
        }
    });

    $('#in-title').ColorPicker({
        color: '222936',
        onShow: function (colpkr) {
            $(colpkr).fadeIn(500);
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).fadeOut(500);
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            $('#titlediv').css('backgroundColor', '#' + hex);
            $('#in-title').css('backgroundColor', '#' + hex);
            createCookie('titleCss', hex);
        }
    });

    var headerCss = readCookie('headerCss')
    var navCss = readCookie('navCss')
    var titleCss = readCookie('titleCss')
    var titleBG = readCookie('titleBG')
    var bodyBG = readCookie('bodyBG')

    if (headerCss != null) {
        $('header').css('backgroundColor', '#' + headerCss);
        $('#in-header').css('backgroundColor', '#' + headerCss);
        $('#faux_header').css('backgroundColor', '#' + headerCss);
    }

    if (navCss != null) {
        $('nav').css('backgroundColor', '#' + navCss);
        $('nav li').css('backgroundColor', '#' + navCss);
        $('.sf-menu li li').css('backgroundColor', '#' + navCss);
        $('.sf-menu li li li').css('backgroundColor', '#' + navCss);
        $('#in-nav').css('backgroundColor', '#' + navCss);
        $('#sidebar').css('backgroundColor', '#' + navCss);
    }

    if (titleCss != null) {
        $('#titlediv').css('backgroundColor', '#' + titleCss);
        $('#in-title').css('backgroundColor', '#' + titleCss);
    }

    if (titleBG != null) {
        if(titleBG!="none"){
			$("#pattern").css("backgroundImage", "url(assets/images/background/" + titleBG + ")");
		} else {
			$("body").css("backgroundImage", "none");
		}
    }

    if (bodyBG != null) {
        if(bodyBG!="none"){
			$("body").css("backgroundImage", "url(assets/images/background/" + bodyBG + ")");
		} else {
			$("body").css("backgroundImage", "none");
		}
    }


    $('#colorChanger').change(function() {
        var str = $(this).val();
        var colors = str.split(',');

        $('header').css('backgroundColor', '#' + colors[0]);
        $('#faux_header').css('backgroundColor', '#' + colors[0]);
        $('nav, nav li, .sf-menu li li, .sf-menu li li li, #sidebar').css('backgroundColor', '#' + colors[1]);
        $('.pagetitle').css('backgroundColor', '#' + colors[2]);
        $('#in-header').css('backgroundColor', '#' + colors[0]);
        $('#in-nav').css('backgroundColor', '#' + colors[1]);
        $('#sidebar').css('backgroundColor', '#' + colors[1]);
        $('#in-title').css('backgroundColor', '#' + colors[2]);

        //update cookies
        createCookie('headerCss', colors[0]);
        createCookie('navCss', colors[1]);
        createCookie('titleCss', colors[2]);
    });

});

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name, "", -1);
}
// /cookie functions
function changeTitlePattern() {
    var imgfile = $("#titlepattern").val();
    //alert("url(assets/images/background/"+imgfile+")");
    $("#pattern").css("backgroundImage", "url(assets/images/background/" + imgfile + ")");
    createCookie('titleBG', imgfile);
}

function changeBGPattern() {
    var imgfile = $("#backgroundpattern").val();
    //alert("url(assets/images/background/"+imgfile+")");
	$("body").css("backgroundImage", "url(assets/images/background/" + imgfile + ")");
    createCookie('bodyBG', imgfile);
}

function changePreset(){
	var preset = $("#preset").val();
    var presets = preset.split(",");
    $('header').css('backgroundColor', presets[0]);
    $('#in-header').css('backgroundColor', presets[0]);
    $('#faux_header').css('backgroundColor', presets[0]);
    $('#in-header').ColorPickerSetColor( presets[0]);
    
    $('nav').css('backgroundColor', presets[1]);
    $('nav li').css('backgroundColor', presets[1]);
    $('#in-nav').css('backgroundColor', presets[1]);
    $('#sidebar').css('backgroundColor', presets[1]);
    $('#in-nav').ColorPickerSetColor( presets[1]);
    
    $('#titlediv').css('backgroundColor',  presets[2]);
    $('#in-title').css('backgroundColor',  presets[2]);
    $('#in-title').ColorPickerSetColor( presets[2]);
    
    createCookie('headerCss', presets[0].replace("#",""));
    createCookie('navCss', presets[1].replace("#",""));
    createCookie('titleCss', presets[2].replace("#",""));
    if(presets[3]!="none"){
		$("#pattern").css("backgroundImage", "url(assets/images/background/" + presets[3] + ")");
	} else {
		$("body").css("backgroundImage", "none");
	}
    createCookie('titleBG', presets[3] );
    if(presets[4]!="none"){
		$("body").css("backgroundImage", "url(assets/images/background/" + presets[4] + ")");
	} else {
		$("body").css("backgroundImage", "none");
	}
    createCookie('bodyBG', presets[4]);
}