$(function(){
  
  // Placeholders support
  // -----------------------------------------------------------------
  var showPlaceholders = function(){
    if(!Modernizr.input.placeholder){
     $("input").each(function(){
	  	var ph_field=this;
		var ph_form=$(ph_field).parent("form");
       if($(this).val()=="" && $(this).attr("placeholder")!=""){
		   $(this).val($(this).attr("placeholder"));
         $(this).addClass("placeholder");
         $(this).focus(function(){if($(this).val()==$(this).attr("placeholder")) $(this).val("").removeClass("placeholder");});
         $(this).blur(function(){if($(this).val()=="") $(this).val($(this).attr("placeholder")).addClass("placeholder");});
       }
		 // make sure we don't submit the place holder content
		 if($(ph_field).attr("placeholder")!=undefined){
		 $(ph_form).submit(function(event){
				if($(ph_field).val()==$(ph_field).attr("placeholder"))$(ph_field).val("")
			})
		 }		 
     });
    }
  };
  showPlaceholders();

 
	// Store locator form
	// -----------------------------------------------------------------
	$("#store-form").submit(function(event){
		event.preventDefault();
		searchStores()
	});
	function searchStores(){
		var criteria=$("#store_criteria").val(),
				fitness=$("#store_fitness").is(":checked"),
				site=$("#store_site").val();
		// request the results via AJAX
		$.ajax({
			url:$("#store-form").attr("action"),
			data:"store.criteria="+criteria+"&store.fitness="+fitness,
			success:function(data){
				addMarkers(data,true,site);
				// send the string'd JSON to the listing
				strJSON=JSON.stringify(data);
				$("#store-results-listing").load("/"+site+"/store/listing/?cache="+Math.random(),{result:strJSON})
			},
			error:function(xmlhttprequest,textstatus,errorthrow){
				alert("Sorry, your search returned no results")		
			}
		});
	}
  
  // Country/Language select
  // -----------------------------------------------------------------
  var openCountryList = function(el){
    var countryList = el.parent("div").find(".country-list");
    $("body").addClass("country-list-opened");
    countryList.find("ul ul").hide();
    countryList.css("height","60px").show();
    return false;
  };
  var closeCountryList = function(){
    $(".country-list").hide();
    $("body").removeClass("country-list-opened");
    return false;
  };
  var selectCountry = function(name){
    alert("Selected country/language: "+name);
    closeCountryList();
    return false;
  };
  $(".open-country-selector").click(function(){
    openCountryList($(this));
    return false;
  });
  $("div.country-close a").click(function(event){
  	event.preventDefault();
	closeCountryList()
  })
  /*$(".country-list a").click(function(){
    var name = $(this).attr('title');
    selectCountry(name);
    return false;
  });*/
  $(".flag").hover(function(){
    var flag = $(this);
    $(this).siblings().stop().animate({opacity:0.3},{duration:300});
    if($(this).hasClass("multiple")){
      $(this).parents(".country-list").stop().animate({height:78}, 200, function(){flag.find("ul").fadeIn();});
    }
  }, function(){
    $(this).siblings().stop().animate({opacity:1},{duration:300});
    $(this).parents(".country-list").stop().animate({height:60}, 200);
    $(this).find("ul").fadeOut('fast');
  });
  
  
  
  // Navigation (no border when hovering)
  // -----------------------------------------------------------------
  $("#nav ul > li.n-bdr").hover(function(){
    $(this).prev().addClass("no-border");
  }, function(){
    $(this).prev().removeClass("no-border");
  });
  
  
  
  // Navigation Map accordion
  // -----------------------------------------------------------------
  if($("#map-accordion").length){
    //$("#map-accordion").accordion({collapsible:true});
  }
  
  
  // Home
  // -----------------------------------------------------------------
  if($("body").hasClass("home")){
    
    // Hero slider
    if($("#hero-slider").length){
      $("#hero-slider").anythingSlider({
        resizeContents:false,
        startPanel:1,
        hashTags:false,
        buildArrows:false,
        buildNavigation:true,
        navigationFormatter:null,
        forwardText:"&raquo;",
        backText:"&laquo;",
        autoPlay:true,
        startStopped:false,
        pauseOnHover:true,
        resumeOnVideoEnd:true,
        stopAtEnd:false,
        playRtl:false,
        startText:"Start",
        stopText:"Stop",
        delay:7000,
        animationTime:600,
        easing:"swing"
      });
    }
    
    // Home tabs
	 if($("#home-tabs-top").length){
	 	$("#home-tabs-top a").each(function(){
			var gchange=$(this).attr("href");
			var gg=gchange.replace("#h-tab-","");
			$(this).click(function(event){
				event.preventDefault();
				$("div.sector").hide();
				$(gchange).show();
				$("#home-tabs-top").attr("class","home-tabs-"+gg)
			})
		})
	 }
    
  }
  
  
  
  // Catalogue page
  // -----------------------------------------------------------------
  
  if($("body").hasClass("catalogue") || $("body").hasClass("home")){
    
    // Show alternative colors popover
    $(".shoe-list li").hover(function(){
      var popover = $(this).find(".altcolors");
      $(this).addClass("shoe-hover");
      $(this).siblings().addClass("shoe-default");
      popover.show(0,function(){
			$(this).find("img.sml-loader").each(function(){
				$(this).attr("src",$(this).attr("data-src"));
			})
		});
      popover.position({
        of: $(this),
        my: "left top",
        at: "left bottom",
        offset: "-20 -20",
        collision: "flip none"
      });
    }, function(){
	 	// show the shoes
      $(this).removeClass("shoe-hover");
      $(this).siblings().removeClass("shoe-default");
      $(this).find(".altcolors").hide();
    });
	}
    
     if($("body").hasClass("catalogue")){
    // Give width to selected items' list
    var giveWidthToSelected = function(){
      $(".refine-by-items > li").each(function(){
        var itemClass = $(this).attr("class");
        var itemWidth = $(this).width();
        var itemSelected = "." + itemClass + "-selected";
        $(itemSelected).css("width",itemWidth+28);
        $(itemSelected).find(".inner-list").css("width",itemWidth);
      });
    };
    giveWidthToSelected();
    
    // Hide list
    var hideItemList = function(el){
      var itemsList = el.parents("li");
      var itemsInnerList = el.parents(".inner-list");
      itemsInnerList.children("div").remove();
      itemsList.addClass("hidden");
    };
    
    // Remove selection
    /*$(".remove-selection").click(function(){
      var selectedItem = $(this).parent("div");
      var itemsList = $(this).parents("li");
      var itemsInnerList = $(this).parents(".inner-list");
      selectedItem.remove();
      if(!itemsInnerList.has("div").length){
        itemsList.addClass("hidden");
      }
      return false;
    });*/
    
    // Clear choices
   /* $(".clear-choices").click(function(){
      hideItemList($(this));
      return false;
    });*/
    
    
  }
  
  
  
  
  // Detail page
  // -----------------------------------------------------------------
  
  if($("body").hasClass("detail")){

    $("#p-tabs").tabs();
    
    $(".collapse").click(function(){
      if($(this).parents(".collapsible").hasClass("opened")){
        $(this).parents(".collapsible").removeClass("opened");
        $(this).parents(".collapsible").find(".inner-content").slideUp("fast");
      } else {
        $(this).parents(".collapsible").addClass("opened");
        $(this).parents(".collapsible").find(".inner-content").slideDown("fast");
      }
      return false;
    });
    
    // Image magnifier
    if (!$.browser.msie){
      $(".shoe-zoomed").loupe();
      $(".shoe-zoomed").click(function(){
        return false;
      });
    }
	 
	 $("a.change-zoom").click(function(event){
	 	event.preventDefault();
		var large=$(this).attr("data-large"),xlarge=$(this).attr("data-xlarge");
		$('.loupe img').attr('src',xlarge);
		$('#shoe-zoomed-large').attr('src',xlarge);
		$("div.shoe-sides ul li").removeClass("active");
		$(this).parent("li").addClass("active")
	 })
    
  }
  
  
  
  // Overlay
  // -----------------------------------------------------------------
  var overlay = $("<div />");
  overlay.addClass("overlay");
  $("body").append(overlay);
  
  var showOverlay = function(){
    overlay.show();
  };
  var hideOverlay = function(){
    overlay.fadeOut("fast");
  };
  
  
  
  // Open popover (ex. <a href="#ask" class="open-popover"></a>)
  // -----------------------------------------------------------------
  $(".open-popover").click(function(){
    var pop = $(this).attr("href");
    $(pop).show().addClass("active");
    showOverlay();
    return false;
  });
  
  
  
  // Close popover
  // -----------------------------------------------------------------
  $("a[href=\"#close\"]").click(function(){
    $(".popover.active").removeClass("active").hide();
    hideOverlay();
    return false;
  });
  
  
  
  // Submit form button
  // -----------------------------------------------------------------
  $("a.submit").click(function(){
    $(this).parents("form").submit();
    return false;
  });
  
  
  
  // Buzz Section
  // -----------------------------------------------------------------  
 
 
 
 
if($("body").hasClass("buzz-section")){
	
	// collect some important values
	var dims={
		window:$("#media-holder-centre").width(),
		track:$("#media-holder-track").width(),
		ul:$("#media-ul").width()
	}
	
	// capture the click of the next/prev buttons 
	$("div.media-button a").click(function(event){
		event.preventDefault();
		if(!$(this).hasClass("disabled")){
			var direction=$(this).attr("rel");
			//move it
			adSlide(direction);
		}
	});
	// capture the jump thumbs
	$("a.slider-jump").click(function(event){
		event.preventDefault();
		var row=$(this).attr("data-row");
		adSlide("jump",row)
	});
	
	function adSlide(mode,row){
		// direction specific stuff 
		var curr_pos=parseInt($("#media-holder-slider").css("left").replace("-",""));
		if(curr_pos=="NaN"){curr_pos=0};
		var curr_row=curr_pos/dims.window+1;
		switch(mode){
			case "next":
				//var slide="-="+dims.window;
				// ^ don't work on large sliders, go figure!
				var val=((curr_row+1)*dims.window)-dims.window;
			break;
			case "prev":
				//var slide="+="+dims.window;		
				// ^ don't work on large sliders, go figure!
				var val=((curr_row-1)*dims.window)-dims.window;
			break;
			case "jump":
				//var slide="-"+parseInt(row)+parseInt(dims.window)+"px"
				var val=(row*dims.window)-dims.window;
			break;
		}
		slide="-"+val+"px";
		// animate
		$("#media-holder-slider").animate({
			left:slide
		},"fast",function(){
			disableBtns()
		})
	}
	
	function disableBtns(){
		var left=$("#media-holder-slider").css("left"),
				unsigned=left.replace("-","").replace("px",""),
				maxed=parseInt(unsigned)+parseInt(dims.window);
		// prev
		if(parseInt(left) >= 0){$("div.media-button a.prev").addClass("disabled")}else{$("div.media-button a.prev").removeClass("disabled")}
		// next
		if(maxed >= dims.ul){$("div.media-button a.next").addClass("disabled")}else{$("div.media-button a.next").removeClass("disabled")}
	}
	
}








 
 
 /* if($("body").hasClass("buzz-section")){
    
    $("#ads_slider")
      .anythingSlider({
        resizeContents:false,
        startPanel:1,
        hashTags:false,
        buildArrows:true,
        buildNavigation:false,
        navigationFormatter:null,
        forwardText:"&raquo;",
        backText:"&laquo;",
        autoPlay:false,
        startStopped:false,
        pauseOnHover:true,
        resumeOnVideoEnd:true,
        stopAtEnd:true,
        startText:"Start",
        stopText:"Stop",
        delay:3000,
        animationTime:0,
        easing:"swing"
      })
      
      .anythingSliderFx({
        inFx: {
          'div':{opacity:1,time:500}
        },
        outFx: {
          'div':{opacity:0,time:0}
      }
      
   });
     

    // Thumbnail Link
    $("#media-thumbnail ul li a").click(function(){
      var new_slide = $(this).attr("rel");
      $('#ads_slider').anythingSlider(new_slide);
      return false;
    });
    
    

  }*/
  
  
  
  
  
  
  
  
  // TO BE REMOVED - ONLY FOR DEMO
  if($(".popover").length){
    $(".popover").show();
    showOverlay();
  }
  
      // Fitness Main Navigation hover effect
    $(".dropdown-fit-list a").hover(function(){
      if(!$(this).hasClass("active")){
        var theimg = $(this).find("img");
        fitNavSrc = theimg.attr("src");
        var newsrc = fitNavSrc.split(".")[0];
        theimg.attr("src",newsrc+"-active.png");
      }
    }, function(){
      if(!$(this).hasClass("active")){
        var theimg = $(this).find("img");
        theimg.attr("src",fitNavSrc);
      }
    });
  
});

$(function(){

  // Fitness page
  // -----------------------------------------------------------------
  if($("body").hasClass("fitness")){
    
    // Men / Women switch
    $(".switch-women").click(function(){
      var parent = $(this).parents('.fit-switch');
      $('.switch-men',parent).removeClass('selected');
      $(this).addClass('selected');
      $('.checkbox',parent).attr('checked', true);
		location.href=$(this).attr("data-jump");
    });
    $(".switch-men").click(function(){
      var parent = $(this).parents('.fit-switch');
      $('.switch-women',parent).removeClass('selected');
      $(this).addClass('selected');
      $('.checkbox',parent).attr('checked', false);
		location.href=$(this).attr("data-jump");
    });
    
    
    // Content hover map
    $(".hovermap-popup").each(function(){
      var mapDot = $(".hovermap a[href=\"#"+$(this).attr("id")+"\"]"),
          popMy = $(this).attr("data-my"),
          popAt = $(this).attr("data-at"),
          popOffset = $(this).attr("data-offset"),
          arrowPos = popMy.split(" ")[0];
      
      $(this).append("<span class=\"arrow-"+arrowPos+"\"></span>");
      
      $(this).position({
        of: mapDot,
        my: popMy,
        at: popAt,
        offset: popOffset,
        collision: "none none"
      });
      
    })
    
    
    $(".hovermap a").click(function(){
      return false
    });
    
    $(".hovermap-popup").hide();
    
    $(".hovermap a").hover(function(){
      var target = $(this).attr("href");
      $(target).addClass("active");
      $(target).stop().show();
    }, function(){
      var target = $(".hovermap-popup.active");
      $(target).removeClass("active");
      $(target).stop().hide();
    });
    
    
    // Fitness Secondary Nav hover effect
    var fitSecNavSrc = "";
    $(".fit-sec-nav li").hover(function(){
      if(!$(this).hasClass("active")){
        var theimg = $(this).find("img");
        fitSecNavSrc = theimg.attr("src");
        var newsrc = fitSecNavSrc.split(".")[0];
        theimg.attr("src",newsrc+"-active.png");
      }
    }, function(){
      if(!$(this).hasClass("active")){
        var theimg = $(this).find("img");
        theimg.attr("src",fitSecNavSrc);
      }
    });
    
    
  }
  
	// placeholder replace for search
	if($("body").hasClass("img-placeholder")){
		revealImg();
		$(window).scroll(revealImg);
		$(window).resize(revealImg);
	}

});

function revealImg(){
	// var the browser info
	var browser={
		height:$(window).height(),
		top:$(window).scrollTop()
	}
	browser.pos=browser.height+browser.top;
	// loop all placeholder images
	$("img.img-loader").each(function(){
		var img={
			top:$(this).offset().top,
			src:$(this).attr("data-img"),
			id:$(this).attr("id")
		}
		if(img.top <= browser.pos){
			// its in the user's view, so show the real img
			$(this).attr("src",img.src);
		}
	});
}


