jQuery.fn.preventDoubleSubmit = function() {
  jQuery(this).submit(function() {
    if (this.beenSubmitted)
      return false;
    else
      this.beenSubmitted = true;
  });
};

$(document).ready(function () {
	//$(".nav li:last-child A").addClass("lastChild");
	$(".menuchild li:first-child A").addClass("firstChild");
	
	$(".nav").append("<li class=\"lastchild\"></li>"); // RM - 20100331
	$(".menuchild").append("<li class=\"lastchild\"></li>"); // RM - 20100331
	$("INPUT[type=checkbox]").addClass("checkbox");
	
	Watermark("#txtSearch","Search...",false);
	Watermark("#username","Username",false);
	Watermark("#password","Password",true);
	
	$("#search").submit(function(){
	    var query = $("#txtSearch").val();
	    if (window.location.host == "staging.pauleycreative.co.uk")
	        window.location = "http://staging.pauleycreative.co.uk/dvd2012/Search/" + query.replace(/\./g,' ');
	    else
    	    window.location = "/Search/" + query.replace(/\./g,' ');
    	return false;
    });
    
    var selection = ".nav li a[rel="+getCookie('menuselection')+"]";
    $(selection).each(function(){$(this).addClass('selected')});
    setCookie('menuselection','',1);
    
    $(".nav li a").click(function(){
        setCookie('menuselection',$(this).attr('rel'),1);
    });
    
    $('#createform').validate();
    //$('form').preventDoubleSubmit();//does not work with validation
    $("input.number").numeric();
    
    $('#fader').cycle({ cleartype: 0 });
});

function Watermark(selector, value, isPassword) {
    var watermark = value;
    if ($(selector).val() == "") {
        $(selector).val(watermark);
    }
    $(selector).focus(function () {
        if (this.value == watermark) {
            this.value = "";
            if (isPassword) 
            {
                var password = $(this).clone(true).attr('type','password');
                $(this).after(password);
                $(password).focus()
                $(this).remove();
            }
        }
    }).blur(function () {
        if (this.value == "") {
            this.value = watermark;
            if (isPassword)            
            {
                var password = $(this).clone(true).attr('type','text');
                $(this).after(password);
                $(this).remove();
            }
        }
    });
}
function setCookie(c_name,value,expiredays)
{var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);document.cookie=c_name+"="+escape(value)+
((expiredays==null)?"":";expires="+exdate.toGMTString());}
function getCookie(c_name)
{if(document.cookie.length>0)
{c_start=document.cookie.indexOf(c_name+"=");if(c_start!=-1)
{c_start=c_start+c_name.length+1;c_end=document.cookie.indexOf(";",c_start);if(c_end==-1)c_end=document.cookie.length;return unescape(document.cookie.substring(c_start,c_end));}}
return"";}

/*
  @author: remy sharp / http://remysharp.com
  @params:
    feedback - the selector for the element that gives the user feedback. Note that this will be relative to the form the plugin is run against.
    hardLimit - whether to stop the user being able to keep adding characters. Defaults to true.
    useInput - whether to look for a hidden input named 'maxlength' instead of the maxlength attribute. Defaults to false.
    words - limit by characters or words, set this to true to limit by words. Defaults to false.
  @license: Creative Commons License - ShareAlike http://creativecommons.org/licenses/by-sa/3.0/
  @version: 1.2
  @changes: code tidy via Ariel Flesler and fix when pasting over limit and including \t or \n
*/

(function ($) {

$.fn.maxlength = function (settings) {

    if (typeof settings == 'string') {
        settings = { feedback : settings };
    }

    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    function trim(stringToTrim) {
    	return stringToTrim.replace(/^\s+|\s+$/g,"");
    }

    function length(el) {
    //removed trim as was causing problems
        el.value = el.value;
    	var parts = el.value;
    	if ( settings.words )
    	{
    		parts = el.value.length ? parts.split(/\s+/) : { length : 0 };
    		var temp = el.value;
    		var hyphens = el.value.length ? temp.split(/\s[–]/): { length : 0};
    		return parts.length - hyphens.length;
    	}
    	return parts.length;
    }
    
    return this.each(function () {
        var field = this,
        	$field = $(field),
        	$form = $(field.form),
        	limit = 100,//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 false;//settings.words && code != 32 && code != 13 && len == limit;
            }
        }
        function AlertOver() {
            alert('You have exceeded the word limit please ensure you have pasted only 100 words');
            return "";  
        }

        var updateCount = function () {
            var len = length(field) - 1,
            	diff = limit - len;
            $charsLeft.html( diff - 1 || "0" );

            // truncation code
            if (settings.hardLimit && diff < 0) {
                    field.value = settings.words ? 
            	    // split by white space, capturing it in the result, then glue them back
            	    AlertOver() :
            		//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 : '.charsLeft',
    words : false
};

})(jQuery);
