(function ($) {

	//parent-child checkbox behaviour
	$('li.ganged input.parent').click(function() {
		if (!$(this).attr('checked')) {
			$(this).parent('li').children('ol').children('li').children('input.child').attr('checked', false);
			$(this).parent('li').children('ol').children('li').children('input.child').attr('disabled', true);
		} else {
			$(this).parent('li').children('ol').children('li').children('input.child').attr('disabled', false);
		};
		
	});
	
	
	//Show-Hide on input value change... data value can be delimited by pipes (|)
	$('.show-hide-on-input input').live("change", function(e) {
		var cls = $(this).parents('.show-hide-on-input').attr("data-class");
		var v = $(this).parents('.show-hide-on-input').attr("data-value").split("|");
		console.log(v);
		for(i=0; i <= v.length; i++){
			if ($(this).val() == v[i]) {
				$('.' + cls).show('fast');
				break;
			}
			else {
				$('.' + cls).hide('fast');
			}
		}
	});
	
	$('.delete').click(function() {
		return confirm("Are you sure you want to delete this?");
	});

	$('.confirm').live("click", function() {
		var msg = $(this).attr("data-confirm-msg");
		return confirm(msg);
	});


	$('.locale-selector form select').change(function() {
		$("body").prepend("<div id='modal'/>");
		$(this).parent("form").submit();
	});
	
	
    $("select#country.address-field").change(function(){ 
        var country = $('select#country.address-field option:selected').val();
		var dialingCode = $('select#country.address-field option:selected').attr("data-dialing-code") ?  $('select#country.address-field option:selected').attr("data-dialing-code"):"";
			dialingCode += " ";
		var state = $('#state');
		
		var fillOptions = function(newOptions){
			var options = document.getElementById('state').options;
			$('option', state).remove();
				
			$.each(newOptions, function(code) {
			   options[options.length] = new Option(newOptions[code], newOptions[code]);
			 });
			 options[0] = new Option( "Select...","");			 
		};
		
		var list = "";
        switch (country) {
            case "Australia":	
				list = state.attr("data-au").split(",");	
				fillOptions(list);
				$("#state-li").show();
                break;
				
            case "United States of America":
				list  = state.attr("data-us").split(",");	
				fillOptions(list);
				$("#state-li").show();
                break;
				
			default: 
				$("#state-li").hide();
		}
		// phone
		$('#phone-day').parent().contents().filter(function(){ return this.nodeType != 1; }).wrap("<span class='orphan'/>");
		$('#phone-mobile').parent().contents().filter(function(){ return this.nodeType != 1; }).wrap("<span class='orphan'/>");
		$('#phone-evening').parent().contents().filter(function(){ return this.nodeType != 1; }).wrap("<span class='orphan'/>");

		$('span.orphan').remove();
		
		$('#phone-day').before(dialingCode);
		$('#phone-mobile').before(dialingCode);
		$('#phone-evening').before(dialingCode);		
		
    });
	 

								
	if (!$("div#pop-edit").length){
		$('<div/>', { id: 'pop-edit'}).appendTo("body");
	}
	
	$(".clear-on-click").click(function() {
		// If contents equal to label then clear		
		if ($(this).val() == $(this).attr('data-label')) {
			$(this).val('');
		}
		return false;
	});
	
	// Smart more
	$(".smart-more").each(function() {
		//var content = jQuery.trim($(this).text());
		var content = jQuery.trim($(this).text());
		var chars = $(this).attr('data-chars');
		if(chars == undefined) {
			chars = 140; // default length;
		}
		if(content.length > chars) {
			var teaser = content.substring(0, chars);
			$(this).text(teaser).append('... <span style="display:none;">' + content + '</span><a href="#">[More]</a>');
			$(this).find('a').click(function() {
				var content = $(this).parent().find('span').text();
				$(this).parent().html(content);
				return false;
			});
		}
		return false;
	});

	// Dynamic tabs
	$('.tabs-26px .tabs-26px-header ul li a').click(function(e) {

		if($('#' + $(this).parents('li').attr('data-target')).val() != undefined) {

			var tabClicked = $(this).parents('li').attr('id');
			if(!tabClicked) {
				tabClicked = $(this).parents('li').attr('data-target');
			}
			var variable = $(this).parents('ul').attr('data-variable');

			_setVariable(variable, tabClicked);

			$(this).parents('ul').find('li').removeClass('selected');
			$(this).parents('li').addClass('selected');

			$(this).parents('ul').find('li').each(function() {
				$('#' + $(this).attr('data-target')).hide();
			});

			// ...then show the one selected 
			$('#' + $(this).parents('li').attr('data-target')).show();

			return false;
		}
	});
	
	
	
	$.fn.menutip = function(contentId, menuItemId, yOffset) {
		qTipContent = $('#'+contentId);	
		return this.qtip({
			content: qTipContent,
			show: {event: 'mouseover'},
			hide: {fixed: true},
			position: {
				adjust: {x: 0,y: yOffset},
				at: 'bottom center',
				my: 'top center',
				viewport: $(window),
				container: $('#primary-nav-container'),
				target:$('#primary-nav-container')
			},
			style: {
					classes:'section-nav-tooltip ui-tooltip-shadow ui-tooltip-light',
					tip: false
				},	
			events: {
				show: function(event, api) {secondaryNavigationOnShow(menuItemId);},
				hide: function(event, api) {secondaryNavigationOnHide(menuItemId);}
			}
		});
	};
	
	/*
NOW SLIGHLTY DIFFERENT FOR RENTER VS. MANAGER - MAY MERGE AGAIN LATER
	$.fn.menutip = function(url, id) {
		return this.qtip({
			content: { text: 'Loading...', ajax : url},
			show: {event: 'mouseover'},
			hide: {fixed: true},
			position: {
				adjust: {x: 0,y:-7},
				at: 'bottom center',
				my: 'top center',
				viewport: $(window),
				container: $('#primary-nav-container'),
				target:$('#primary-nav-container')
			},
			style: {
					classes:'section-nav-tooltip ui-tooltip-shadow ui-tooltip-light',
					tip: false
				},	
			events: {
				show: function(event, api) {secondaryNavigationOnShow(id);},
				hide: function(event, api) {secondaryNavigationOnHide(id);}
			}
		});
	};
	
*/
	
	// Modal edit dialog trigger
	$('a.edit-modal').live("click", function(e) {
		if(e.button == 0) { //  this is about intercepting left click only
			$("div#pop-edit").empty();
			$("div#pop-edit").append("<div class='search-field-loading' >&nbsp;</div");

			setUpDialog($(this));
			$("div#pop-edit").dialog('open');
			$.get($(this).attr("href") , {ajax: true}, function(data) {
				$("div#pop-edit").empty();
				$("div#pop-edit").append(data);
			})
			
		}
		else {
			return true;
		}

		return false;
	});
	
		// Modal edit dialog trigger
	$('form.edit-modal').live("submit", function(e) {		
			$("div#pop-edit").empty();
			$("div#pop-edit").append("<div class='search-field-loading' >&nbsp;</div");
			setUpDialog($(this));
			$("div#pop-edit").dialog('open');			
			$.post($(this).attr("action") , $(this).serialize(), function(data) {
				$("div#pop-edit").empty();
				$("div#pop-edit").append(data);
			})
			
		return false;
	});

	$('div#pop-edit #cancel').live("click", function(e) {
		$('div#pop-edit').dialog('close');
		return false;
	});
	
	
	// Show drop down on mouse click
	$("div.drop-down > a:first-child").click(function(e) {
		$(this).parent().children("div").toggle();
		$(this).parent().toggleClass('open');
		return false;
	});

	// Show drop down on mouse hover
	$("div.drop-down.hover > a:first-child").hover(function(e) {
		$(this).parent().children("div").show();
		$(this).parent().addClass('open');
		return false;
	});


	// Hide all drop downs on mouse leave
	$("div.drop-down div").bind('mouseleave', function() {
		$(this).hide();
		$(this).parent().removeClass('open');
		return false;
	});


	// Show drop down on mouse click
	$("div.button-drop-down a.drop-down").click(function(e) {
//		$(this).parent("dl").children("dd").toggle();
		$(this).parent().parent().toggleClass('open');
		return false;
	});


	// Show drop down on mouse hover - FOR BUTTONS
	$("div.button-drop-down.hover a.drop-down").hover(function(e) {
//		$(this).parent().children("div").show();
		$(this).parent().parent().addClass('open');
		return false;
	});


	// Hide all drop downs on mouse leave - FOR BUTTONS
	$("div.button-drop-down dd").bind('mouseleave', function() {
		$(this).parent().removeClass('open');
		return false;
	});
	
	$(".mood a").click( function(){
		// ajax links for mood
		var mood = $(this).attr("data-mood");
		$.get($(this).attr("href") , {ajax: true}, function(data) {
			$(".mood div").removeClass();
			$(".mood div").addClass("mood-" + mood);
		})
		return false;
	});


	
})(jQuery);
///-- end doc ready



var setUpDialog = function (obj) {

	var modal = obj.hasClass("modal");

	//position			
	var position = [215, 60];
	if(obj.dataset("position")) {
		position = eval(obj.dataset("position"));
	}

	//draggable
	var draggable = true;
	if(obj.dataset("draggable")) {
		draggable = eval(obj.dataset("draggable"));
	}

	//width
	var width = 620;
	if(obj.dataset("width")) {
		width = eval(obj.dataset("width"));
	}

	//height
	var height = 'auto';
	if(obj.dataset("height")) {
		height = eval(obj.dataset("height"));
	}

	//modal
	var modal = false;
	if(obj.dataset("modal")) {
		modal = eval(obj.dataset("modal"));
	}

	//zIndex
	var zIndex = 7000;
	if(obj.dataset("zIndex")) {
		zIndex = eval(obj.dataset("zIndex"));
	}

	//title
	var title = "";
	if(obj.dataset("title")) {
		title = obj.dataset("title");
	}

	$('div#pop-edit').dialog({
		autoOpen: false,
		position: position,
		draggable: draggable,
		width: width,
		height: height,
		zIndex: zIndex,
		modal: modal,
		title: title
	});
};


var secondaryNavigationOnShow = function (id) {
	if (!(id === undefined)) {		
		var $menuDiv = $('#' + id + ' div');
		$menuDiv.addClass("secondary-nav-show");		
		$menuDiv.find('a').css("color",'#fff');		
	}
};


var secondaryNavigationOnHide = function (id) {
		if (!(id === undefined)) {		
		var $menuDiv = $('#' + id + ' div');		
		$menuDiv.removeClass("secondary-nav-show");
		$menuDiv.find('a').removeAttr("style");
	}
};


	Date.prototype.addHours= function(h){
	    this.setHours(this.getHours()+h);
	    return this;
	}

	var findIndex =  function(value,arrayToSearch){
		var ctr = 0;
		for (var i=0; i < arrayToSearch.length; i++) {
			if (arrayToSearch[i] == value) {
				return i+1; // start at 1 not zero indexed so the first item returns 1 not 0
			}
		}
		return ctr;
	};


// display maxlength
(function($) {

	$.fn.maxlength = function(settings) {

		if(typeof settings == 'string') {
			settings = {
				feedback: settings
			};
		}

		settings = $.extend({}, $.fn.maxlength.defaults, settings);

		function length(el) {
			var parts = el.value;
			if(settings.words) parts = el.value.length ? parts.split(/\s+/) : {
				length: 0
			};
			return parts.length;
		}

		return this.each(function() {
			var field = this,
				$field = $(field),
				$form = $(field.form),
				limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
				$charsLeft = $form.find(settings.feedback);

			function limitCheck(event) {
				var len = length(this),
					exceeded = len >= limit,
					code = event.keyCode;

				if(!exceeded) return;

				switch (code) {
				case 8:
					// allow delete
				case 9:
				case 17:
				case 36:
					// and cursor keys
				case 35:
				case 37:
				case 38:
				case 39:
				case 40:
				case 46:
				case 65:
					return;

				default:
					return settings.words && code != 32 && code != 13 && len == limit;
				}
			}


			var updateCount = function() {
				var len = length(field),
					diff = limit - len;
				var percentageLeft = (diff / limit) * 100;

				$charsLeft.html(diff || "0");
				$charsLeft.removeClass('low');
				$charsLeft.removeClass('medium');
				$charsLeft.removeClass('high');

				if(percentageLeft < 10) {
					$charsLeft.addClass('low');
				}
				else if(percentageLeft < 25) {
					$charsLeft.addClass('medium');
				}
				else {
					$charsLeft.addClass('high');
				}

				// truncation code
				if(settings.hardLimit && diff < 0) {
					field.value = settings.words ?
					// split by white space, capturing it in the result, then glue them back
					field.value.split(/(\s+)/, (limit * 2) - 1).join('') : field.value.substr(0, limit);

					updateCount();
				}
			};

			$field.keyup(updateCount).change(updateCount);
			if(settings.hardLimit) {
				$field.keydown(limitCheck);
			}
			updateCount();
		});
	};

	$.fn.maxlength.defaults = {
		useInput: false,
		hardLimit: true,
		feedback: '.character-counter span',
		words: false
	};
	


})(jQuery);

		$('.character-counter').show();								
		$('.character-counted').maxlength({
		    'feedback' : '.character-counter span',
		    'useInput' : false
		});

var _setVariable = function (variable, value) {
	
	$.ajax({
		type: "GET",
		url: "/main/ajaxSetVariable/",
		cache: false,
		data: "variable=" + variable + '&value=' + value,
		success: function(msg) {
			return msg;
		}
	});
}

var _toggleVariable = function (variable, callback) {
	$.ajax({
		type: "GET",
		cache: false,
		url: "/main/ajaxToggleVariable/",
		data: "variable=" + variable,
		success: function(msg) {
			if(msg == 'YES') {
				msg = true;
			}
			else {
				msg = false;
			}
			callback(msg);
		}
	});
}

$.fn.dataset = function(name) {
	if(this.length == 0) {
		// no nodes, return
		return null;
	}
	if(this.length == 1) {
		// for a single node, return value
		if(this[0].dataset != undefined) {
			return this[0].dataset[name];
		}
		// fallback if dataset is not a member of the node
		return this.attr("data-" + name);
	}
	// multiple nodes, return dictionary from object id to value
	var values = {};
	this.each(function(o) {
		values[$(o).attr("id")] = $(o).dataset(name);
	});
	return values;
};

$.fn.hasAncestor = function(a) {
	return this.filter(function() {
		return !!$(this).closest(a).length;
	});
};
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);    
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}
