$(function(){
	var brand = brand || {};
	brand.lang = brand.lang || 'EN'; 
	var langID = /es/i.test(brand.lang) ? 1 : 0;
     //Pagination selector
	 var phrases = {
	 	cityState: "Please enter a zip or a city and state.|Por favor, introduzca un código postal o una ciudad y estado.".split("|"),
		zipCode: "Please enter a valid zip.|Por favor, introduzca un código postal".split("|")
	 }
    $("#perPage").bind("change",function(){
      $("#perPageForm").submit();
    });
    //Prepare ajax global defaults
    $.ajaxSetup({
        type: "GET"
    });
    validate = function(eles){
      var req = {}, reqIdx = 0, chkRequired = false, valid = false, message = '', ele = '';
      for (var i = -1; ele = eles[++i];) { //for shortcut, if ele is undefined it will return false
          if (ele.name.match(/^zip$|^city$|^state$/)) {
              req[ele.name] = {
                  value: ele.value === ele.title ? '' : ele.value,//remove help text if its there
                  pos: i //maintain reference to position in order to set values as needed
              }
              chkRequired = true;
          }
      }
      if(!chkRequired){
        for(var i = -1; ele = eles[++i];) //clear helper text and submit form
          if(ele.value === ele.title) ele.value = '';
        valid = true;
      }
      else{ //validate zip, city, state
        //Zip passed, make sure valid zip
        //Zip, City, State passed, make sure valid zip
        //No zip, make sure city/state exist
        try { 
            if (req.zip.value) {
                if (req.zip.value.match(/^[\d]{5,9}$/)) {
                    if(eles[req.city.pos].value === eles[req.city.pos].title){
                      eles[req.city.pos].value = '';
                      eles[req.state.pos].value = '';
                    }
                    valid = true;
                }
                else {
                    if (req.city.value && req.state.value) {
                      if(eles[req.zip.pos].value === eles[req.zip.pos].title){
                        eles[req.zip.pos].value = '';
                      }
                        valid = true;
                    }
                    else 
                        message += phrases["cityState"][langID]+ "\n";
                }
            }
            else {
                if (req.city.value && req.state.value) {
                    if(typeof req.zip !== 'undefined')
                      eles[req.zip.pos].value = '';
                    valid = true;
                }
                else 
                    message += phrases["zipCode"][langID];
            }
						
        } 
        catch (err) {
          if(typeof console.log !== undefined)
            console.log(err);
        }
      }
      if(!valid){
        alert(message);
      }
      else{
        
      }
      return valid;
    }
    
    switchText = function()
    {
      if ($(this).val() == $(this).attr('title'))
        $(this).val('').removeClass('blur');
      else if ($.trim($(this).val()) == '')
        $(this).addClass('blur').val($(this).attr('title'));
    }
		validateForms = function(){
			$("form").filter(function(){
				return (typeof $(this).data('bypassValidation') == 'undefined') || $(this).data('bypassValidation') === null; //remove forms that have data.bypassValidation
			}).each(function(){
				//this references the form
				var form = $(this), inputs = this.elements, $hints = $($.grep(this.elements, function(a){
					return a.nodeName === "INPUT"
				})); //cast elements to jQuery Objects
				$hints.each(function(){
					if ($.trim($(this).val()) == '') 
						$(this).val($(this).attr('title'));
					if ($(this).val() == $(this).attr('title')) 
						$(this).addClass('blur');
				}).focus(switchText).blur(switchText);
				form.submit(function(){
					return validate(inputs); //Validate
				});
			});
		};
		setTimeout(validateForms,250);  //delay execution of form validation
		//Special price range filter to prevent minimum price or maximum price showing prices less/greater than the other
		
		var 
			$minPrice = $("#minPrice"),
			$maxPrice = $("#maxPrice");
		
		$("#minPrice, #maxPrice").bind('change',function(){
			var self = this,
				selected = parseInt( self.value.replace(/\D/g,'') ,10), //find value selected after casting to number
				other =  self === $minPrice.get(0) ? $maxPrice : $minPrice, //determine options list being refined
				cropHigh = other === $maxPrice; //true crop bigger values from minPrice, false crop smaller values from maxPrice
			other.children("option").show().filter(function(){
				var val = parseInt(this.value.replace(/\D/g,''),10);
				return cropHigh && val <= selected || !cropHigh && val >= selected;
			}).hide();
		});
});