// JavaScript Document
jQuery(document).ready(function () {
    //Javascript enabled warning
    jQuery('.warningBox').remove();
    jQuery('input[type="submit"]').show()

    //Field Highlight and Trim
    jQuery('#orderForm input[type="text"], #orderForm select, #orderForm textarea, #orderForm input[type="password"]').addClass("idleField");
    jQuery('#orderForm input[type="text"], #orderForm select, #orderForm textarea, #orderForm input[type="password"]').focus(function () {
        jQuery(this).removeClass("idleField").addClass("focusField");
        if (this.type == 'text') {
	        if (this.value == this.defaultValue) {
	            this.value = '';
	        }
	        if (this.value != this.defaultValue) {
	            this.select();
	        }
        }
    });
    jQuery('#orderForm input[type="text"], #orderForm select, #orderForm textarea, #orderForm input[type="password"]').blur(function () {
        jQuery(this).removeClass("focusField").addClass("idleField");
        if (jQuery.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });
    
    //Validation Customizations Order Form
    var validator = jQuery("#orderForm").validate({
    	onkeyup: false,
        rules: {
            Contact0FirstName: "required",
            Contact0LastName: "required",
            Contact0Email: {
                required: true,
                email: true
            },
            Contact0PostalCode: {
                required: true
            }
        },
        //Validation messages
        messages: {
            Contact0FirstName: "Enter your First Name",
            Contact0LastName: "Enter your Last Name",
            Contact0PasswordConfirm: {
                required: "Provide a password",
                rangelength: jQuery.format("Enter at least {0} characters")
            },
            Contact0Email: {
                required: "Please enter a valid email address",
                minlength: "Please enter a valid email address"
            },
            Contact0PostalCode: "Enter a valid zip code",
            Checkbox1: "Please agree to the Terms of Service"
        },
        //Error message at top of form
        invalidHandler: function (e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = errors == 1 ? 'There was 1 problem with your submission.<br />The error has been highlighted below.' : 'There were ' + errors + ' problems with your submission.<br />Errors have been highlighted below.';
                jQuery("div.error span").html(message);
                jQuery("div.error").show();
            } else {
                jQuery("div.error").hide();
            }
        },
        showErrors: function (errorMap, errorList) {
			var myQtip, sel;

			//try {
				for (var key in errorMap) {
					//console.log(key + ' : ' + errorMap[key]);				
					
					if (jQuery('#' + key).attr('tooltip') !== undefined) {
						sel = '#' + key + '[tooltip]';
						myQtip = jQuery(sel).qtip('api');
						myQtip.updateContent(errorMap[key], false);
						myQtip.updateWidth();
						myQtip.show();
					}
				}
			//}
			/*
			catch (ex) {
				console.log(ex.toString());
			}
			*/
			
			//********************************
			//Replace this.defaultShowErrors()
			//********************************
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				//this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
			//***********
			//End replace
			//***********
        },        
        //Groups Error Placement
        groups: {
            fullname: "Contact0FirstName Contact0LastName",
            passwords: "Contact0Password Contact0PasswordConfirm",
            billaddress: "Contact0City Contact0State Contact0PostalCode",
            creditinfo: "CreditCard0CardType CreditCard0CardNumber"
        },
        //Custom error element, default is label
        errorElement: "span",
        // the errorPlacement has to take the layout into account
        // Options error.insertAfter("#Contact0LastName"); error.appendTo( element.next().prev() );.children()http://docs.jquery.com/Traversing
        errorPlacement: function (error, element) {
            if (element.attr("name") == "Contact0FirstName" || element.attr("name") == "Contact0LastName") error.insertAfter("#Contact0LastName");
            else if (element.attr("name") == "Contact0Password" || element.attr("name") == "Contact0PasswordConfirm") error.insertAfter("#Contact0PasswordConfirm");
            else if (element.attr("name") == "Contact0PostalCode" || element.attr("name") == "Contact0City" || element.attr("name") == "Contact0State") error.insertAfter("#Contact0PostalCode");
            else if (element.attr("name") == "CreditCard0CardType" || element.attr("name") == "CreditCard0CardNumber") error.insertAfter("#CreditCard0CardNumber");

            else if (element.is(":radio")) error.appendTo(element.parent().next().next());
            else if (element.is(":checkbox")) error.insertAfter(element.next());
            else error.insertAfter(element);
        },
        // set this class to error-labels to indicate valid fields
        success: function (label) {
            label.html("&nbsp;").addClass("checked");
        }
    });
	
	//Colorbox
	jQuery("#cardSecurity").colorbox({iframe:true, width:650, height:500});
	
	//Custom Input
	//jQuery('input[type="checkbox"]').customInput();
	
	//Pickme Box
	jQuery('.pickme li').click( function() {
		jQuery('.selected').removeClass('selected');
		jQuery(this).addClass('selected').find('input').attr('checked','checked');
	});

	//Toggle shipping address
	jQuery('#ShowShipping').change( function() {
		jQuery('#ShippingInfo').toggle();
	});
});

// tooltips
jQuery(document).ready(function() {
	jQuery('[tooltip]').each(function() {
   		jQuery(this).qtip({
	   		content: jQuery(this).attr('tooltip'),
		 	show: {when: false},
		 	hide: 'keyup',
		  	position:{corner:{target:'topRight',tooltip: 'bottomLeft'}},
		  	adjust: {screen: true },
			style: { 
				  width: {max: 300},
				  padding: 5,
				  background: '#F2F2F2',
				  color: '#333333',
				  font:'1em Arial, Helvetica, sans-serif',
				  textAlign: 'left',
				  border: {
					 width: 5,
					 radius: 8,
					 color: '#BFBFBF'
				  },
				  tip: 'bottomLeft'
			}
      	});
   });
});
