$(document).ready(function() {
    InitSite();
   
   $('.four-col li, .article-list li').mouseover(function() {
		$(this).css("cursor", "pointer");
		$(this).css("cursor", "hand");
	});
   
   $('.four-col li, .article-list li').click(function() {
		window.location = $(this).find('A').attr('href');
	});
	//handle Newsletter sign up form
	$("#newsletterCountry").change(function() { 
        var curItem = $(this).attr("value");
        if(curItem == "10"){
			$("#stateFieldset").removeClass("hdn");
			$("#provinceFieldset").addClass("hdn");
		}else{
			$("#stateFieldset").addClass("hdn");
			$("#provinceFieldset").removeClass("hdn");
		}
	    return false;
    });
	
	var currentDDSTate = 0;
	$('#dd-friend-emails').click(function(evt) {
		evt.preventDefault();
		if(currentDDSTate == 0){
			$(this).removeClass("toggle-down");
			$(this).addClass("toggle-up");
			currentDDSTate = 1;
		}else{
			$(this).removeClass("toggle-up");
			$(this).addClass("toggle-down");
			currentDDSTate = 0;
		}
		$("#friend-email-list").toggle();
	});
   
   //$("#newsletterFm").bind("click",submitNewssub); //}
});

/*function submitNewssub(event){
	
	
	//	event.preventDefault();
	
      // var f=$('#newsletterFm');
       
	 var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      if( !emailReg.test($("#newsletterEmail").val()) || !$("#newsletterEmail").val() ){
           $('#newsletterEmail').css("border","solid #ff0000 1px");
            return false;
      };
	  // $('#newsletterFm').css({display: 'none',color: 'white'});
      //  $('#newsletterFm').html("Loading..<img src='/common/image/loadingAnimation.gif' />");
       // $('#newsletterFm').fadeIn('slow');
        $.post(
            "/common/service/act_subscribeemail.cfm", { 
			email:$("#newsletterEmail").val(),   
            lname:$("#newsletterLastName").val(),
			dcs:'1',
			fname:$("#newsletterFirstName").val()
			
			},
			function(data){
				//alert(data);

                
                    //$('#add-res').css({display: 'none'});
                    //$('#newsletterFm').css({color: 'red'});
                    $('#newsletterFm').html("<p>Thank you, you have been added to DCS Appliances Newsletter list.</p>");
                    $('#newsletterFm').fadeIn('slow');
               
            });
}*/
	
function mycallbackform(v,m,f){
 if(v != undefined)
 $.prompt('Thank You!');
}



//GENERIC SITE----------------------------------------------------------------------------->
function InitSite(){
    var timeout    = 500;
    var closetimer = null;
    var ddmenuitem = null;
    var currentLink = null;
    var newMenu = null;
    var navState = null;

    function jsddm_open()
    {   
       //cancel timer and close
       jsddm_canceltimer();
       jsddm_close();
       
       //test to see if this nav item is selected
       navState = $(this).attr("class");
       
       //set the values of the current menu and link items
       newMenu = '#' + $(this).attr("rel");
       currentLink = '#' + $(this).attr("id");
       
       //set new menu to visible
       ddmenuitem = $(newMenu);
	   ddmenuitem.css('visibility', 'visible');
       
       //set the main nav item to selected
       if(navState != "selected"){
        $(this).addClass("selected");
       }
       
       ddmenuitem.bind('mouseover',  jsddm_openSub);
	 //	ddmenuitem.bind('mouseout',  jsddm_timer);
       //bind the mouseover and mouseout events to the sub nav elements
      // $('.leveltwo').bind('mouseover',  jsddm_openSub);
	  // $('.leveltwo').oneTime(timeout,'hide',jsddm_close);
      //	$('.leveltwo').bind('mouseout',  jsddm_timer);
      
    }
    
    //control mouse over on sub nav
    function jsddm_openSub()
    {   
        //cancel timer and close
      jsddm_canceltimer();
       jsddm_close();
       
       //need to add the selected class to the main nav item again
       if(navState != "selected"){
        $(currentLink).addClass("selected");
       }
       ddmenuitem.css('visibility', 'visible');
	   ddmenuitem.bind('mouseout',  jsddm_timer);
	   
    }

    function jsddm_close()
    {  
        if(ddmenuitem){
            ddmenuitem.css('visibility', 'hidden');
            if(navState != "selected"){
                $(currentLink).removeClass("selected");
               }
        } 
    
    }

    function jsddm_timer()
    {  closetimer = window.setTimeout(jsddm_close, timeout);}

    function jsddm_canceltimer()
    {  if(closetimer)
       {  window.clearTimeout(closetimer);
          closetimer = null;}}

    $(document).ready(function()
							   
    {  
		$('.levelone > li > A:not(:first,:last)').bind('click', jsddm_open)
		$('.levelone > li > A:not(:first,:last)').bind('mouseover', jsddm_open)
       	$('.levelone > li > A:not(:first,:last)').bind('mouseout',  jsddm_timer)
    });
    document.onclick = jsddm_close;
	 $(document).ready(function()
							   
	{	
	
      	$('.levelone > li > A:not(:last||:first)').bind('mouseover click', jsddm_open);
      	//$('.levelone > li > A:not(:last)||:first)').bind('mouseout',  jsddm_timer);
		/*  $('body').one(function() { 
   			 jsddm_close;// Hide the menus 
		 }); */
	  
    });
	
	//cufon Initiation
	//temporary test as cufon is not working in IE9 BETA
	if(!$.browser.msie){
		replaceFonts();
		
		//reduce line height for headings
		$("h1 span, h2 span").css("margin-top", "-5px");		
	}else{
		if($.browser.version != 9.0){
			replaceFonts();
			
			//reduce line height for headings
			$("h1 span, h2 span").css("margin-top", "-10px");	
		}
	}
	
	if($.browser.safari || $.browser.opera ){
		$("#kc-available").css("margin-left", "825px");	
	}
	
	if($.browser.opera ){
		$(".new-nav").css("margin-left", "550px");	
	}

}

function replaceFonts(){
	Cufon.replace(['h1, #middleDiv h2, .extras h3, .dishit-results span, #promo-boxes h3, #kc-nav, #fc-subnav, .h3-text, .kc-intro, .kitchen-collection h2, .kc-features-new h3, .kitchen-collection h4, .dyk-tips h3, #dd-form .label'], {hover: true});	
}

function InitCarousel(){
    $('ul.nav-carousel').ready(function(){    
	 	$("div.move ul li").each(function(index) {                     
        $('ul.nav-carousel').append('<li><a class="go'+index+'">&nbsp;</a></li>');         }); 
	});
	$(".move").jCarouselLite({
        visible: 1,
        auto: 6000,
        speed: 1400,
        easing: 'easeInOutCubic',
		btnGo: [".go0", ".go1", ".go2", ".go3", ".go4", ".go5"]
    });
}

//preload images
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

//position compare button
function PositionCompare(){
 var currentWidth = $(window).width() / 2 + 490;
 //alert(currentWidth);
 
 $('input.compare').css("left", currentWidth)
}

//product details
function InitProductDetail(){
	InitTabs();
	
	curTitle = $("H1").html();
	$(".facebook").attr("href", "http://www.facebook.com/sharer.php?u=" + window.location + "&t=" + curTitle);
	$(".tweet").attr("href", "http://twitter.com/home?status=" + window.location);
	
	$('#btnPrintall').click(function() {
		window.open('/product/print.cfm?productuid='+$("#productuid").val()+'&'+'all=all',"mywindow",
    "location=0,status=1,scrollbars=1,width=700,height=900,toolbar=0");
		return false;
	});
	$("#chkSelectallfeature").click(function() {
		$("input[name='chkFeaturesection']").attr('checked', this.checked);		
	});
	$("#chkSelectallspec").click(function() {
		$("input[name='chkSpecsection']").attr('checked', this.checked);		
	});
	$('#btnPrintSelect').click(function() {
		var s_features=''; var s_specs='';
		$("input[name='chkFeaturesection']:checked").each(
			  function() {
				 
				  s_features= this.value + ';' + s_features ; 
			  
			  }
		);	
		$("input[name='chkSpecsection']:checked").each(
			  function() {
				  s_specs= this.value + ';' + s_specs  ; 
			  
			  }
		);	
		
		if (s_features.length ==0 && s_specs.length == 0){
		 $.prompt('Please select some product information section to print.');
		}else
		window.open('/product/print.cfm?productuid='+$("#productuid").val()+'&'+'specs='+s_specs+'&features='+s_features,"mywindow",
    "location=0,status=1,scrollbars=1,width=700,height=900,toolbar=0");
		return false;
	});

}

function InitProductImages(){

    //set initial values for links
    var prevItem = -1;
    var currentItem = 0;
    var nextItem = 1;
    var totalItems = $('#product-thumbs li a').length;
    var galleryImages = new Array();

    $("#product-thumbs li a").each(
        function() {
            galleryImages.push($(this).attr("href"));
            $( this ).bind (
                "click",
                function(evt){
                    evt.preventDefault();

                    prevItem = Number($(this).attr("class")) - 1;
                    currentItem = Number($(this).attr("class"));
                    nextItem = Number($(this).attr("class")) + 1;

                    //populateLinks();

                    var newMainImage = $(this).attr("rel");
                    var newFullImage = $(this).attr("href");

                    $("#large-image").attr("src", newMainImage);
                    $("#gallery-image img").attr("src", newFullImage);
                }
            );
        });

}

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

function checkUserGuide(){
 if (!document.product.fileName.value && !document.product.productType.selectedIndex){
	alert ("Please enter a model number or select a product category from the dropdown menu.");
	return false
	}

}

function InitProductHome(){
    //carousel
    $(".product-home-move").jCarouselLite({
        visible: 1,
        auto: 6000,
        speed: 1400,
        easing: 'easeInOutCubic'
    });
    
    $('#product-home-list LI A').mouseenter(function(evt) {
         evt.preventDefault();
        $(this).parent().addClass("selected");
    });
    $('#product-home-list LI A').mouseleave(function(evt) {
         evt.preventDefault();
        $("#product-home-list LI").removeClass("selected");
    });
    
    $('#product-home-list LI H3 A').mouseenter(function(evt) {
         evt.preventDefault();
        $(this).parent().parent().parent().addClass("selected");
    });
    $('#product-home-list LI H3 A').mouseleave(function(evt) {
         evt.preventDefault();
        $("#product-home-list LI").removeClass("selected");
    });

}

function InitTabs(){
	var curItem = null;
	
	//hide all divs apart from first
	$(".tab-section").each(
        function(intIndex ) {
			if(intIndex == 0){
				curItem = "#" + $(this).attr("id");
				$(curItem).css("display", "block");
			}
        }
    ); 
	
	
	$(".tabs li A").each(
        function() {
            $( this ).bind (
                "click",
                function(evt){
					evt.preventDefault();
					if($(this).attr("href") != curItem){
						$(".tabs li a").removeClass("selected");
						//make selected element
						$(this).addClass("selected");
						//hide current
						$(curItem).css("display", "none");
						curItem = $(this).attr("href");	
						//show new
						$(curItem).css("display", "block");
					}
                }
            );
        }
    ); 
}


function goTo(obj) {
	if(obj.options[obj.selectedIndex].value != "")
	document.location = obj.options[obj.selectedIndex].value;
}

function InitProductList(){
	$("ul#products-list LI").each(function(index) {

		if (!((index+1)%4)) $(this).css("background", "none");
	});
    var count = 0;
	$("#frmProducts").clearForm();

    $( "input" ).click(
        function( objEvent ){
            if(this.checked == true ){
                //check that there are not already 6 items selected
                if(count != 5){
                    count = count + 1;
                    $(this).parent().find('LABEL').css('display', 'none');
                    $(this).parent().find('a.compare').css('display', 'block');
                }else{
					$.prompt('You cannot compare more than 5 items');                 
                    this.checked = false;
                }
            }else{
                count = count - 1;
                $(this).parent().find('LABEL').css('display', 'block');
                $(this).parent().find('a.compare').css('display', 'none');
            }
  
        }
    );

    $( "a.compare" ).click(
        function( objEvent ){
            if(count < 2){
               $.prompt('Please select at least 2 products to compare');
            }else{
               $('#frmProducts').submit();
            }
  
        }
    );
}

 $.fn.clearForm = function() {
        return this.each(function() {
          var type = this.type, tag = this.tagName.toLowerCase();
          if (tag == 'form')
            return $(':input',this).clearForm();
          if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
          else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
          else if (tag == 'select')
            this.selectedIndex = -1;
        });
      };

function OneLink(sHostname){ 
		document.location.href = document.location.protocol + "//" + sHostname + document.location.pathname + document.location.search;
		}

function InitVideoGallery(){
	
	$(".culinary-curious li A").hover(
	  function () {
		$(this).parent().find('span.play').css("visibility", "visible");
	  }, 
	  function () {
		$(this).parent().find('span.play').css("visibility", "hidden");
	  }
	);
	
	$(".culinary-curious li H3 A").hover(
	  function () {
		$(this).parent().parent().find('span.play').css("visibility", "visible");
	  }, 
	  function () {
		$(this).parent().parent().find('span.play').css("visibility", "hidden");
	  }
	  
	);		
}
/*
Old function - needed new style sheet for new DCS layout - michelle 20/10/11 
function InitVideoGallery(){
	
	$(".experience-gallery li A").hover(
	  function () {
		$(this).parent().find('span.play').css("visibility", "visible");
	  }, 
	  function () {
		$(this).parent().find('span.play').css("visibility", "hidden");
	  }
	);
	
	$(".experience-gallery li H3 A").hover(
	  function () {
		$(this).parent().parent().find('span.play').css("visibility", "visible");
	  }, 
	  function () {
		$(this).parent().parent().find('span.play').css("visibility", "hidden");
	  }
	  
	);
	
}*/

function InitShare(){
    curTitle = $("H1").html();
    $(".fb").attr("href", "http://www.facebook.com/sharer.php?u=" + window.location + "&t=" + curTitle);
	
	CompressURL(window.location, function(shorturl) {
		//alert(shorturl);
		$(".tw").attr("href", "http://twitter.com/home?status=" + shorturl);
	});
	
    
	
	var txt = 'Email: &nbsp;<input type="text" id="email"  name="email" value="" /><br/>Message:<br/><textarea id="message" name="message"></textarea>';
	
	$(".em").click(function () {
		$.prompt(txt,{
				 submit: mysubmitfunc,
				 buttons: { Send:true }
				}); 
	});
}

function CompressURL(url,success)
{

	var link = 'http://to.ly/api.php?json=1&longurl=' + encodeURIComponent(url) + '&callback=?';
	$.getJSON(link, function(data){
	success && success(data.shorturl);
	});
}


function populatePDFLink(pdfPath){
	$(".pr").attr("href", pdfPath);	
}


function mysubmitfunc(v,m,f){
	
      an = m.children('#email');
	  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      if(f.email == "" || !emailReg.test(f.email) ){
            an.css("border","solid #ff0000 1px");
            return false;
      };
	  $.post("/common/service/act_email.cfm",
   				{ emailTo: f.email,  message:f.message, file:'http://#cgi.servername#/#cgi.SCRIPT_NAME#?#cgi.Query_string#'},
   					function(data){
								   
							
							an.after('<b>Success</b><p>Your email was sent.</p>');											
						
   					}
				 );
      return true;
} 

jQuery.fn.center = function () { 
    this.css("position","absolute"); 
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px"); 
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px"); 
    return this; 
} 
var s_pre;
$('span.dump').ready(function() {
//	alert('ri');
	
	
   refreshVote();
  
   $('a.dish').click(function(event) {
	 /*  if ($.cookie('dcsrecipe_vote'))
		 s_pre= $.cookie('dcsrecipe_vote'); 
		else s_pre='';*/
		event.preventDefault();   
		
		if ( s_pre.indexOf(';'+$('a.dish').attr("rel"))==-1){
        $.post(
            "/common/service/act_vote.cfm", { 
			voteid:$('a.dish').attr("rel"),
			vote:'1'
			
			},
			function(data){
				
					$.cookie('dcsrecipe_vote',s_pre + ';' + $('a.dish').attr("rel"));                
                    refreshVote();
					$.prompt(txtEm,{callback: mycallbackform, 
				 	submit: submitNewssub,
					buttons: { Submit:true }
				}); 
               
            });
		} else  $.prompt('You have already voted once before.');
		
    });
	 $('a.ditch').click(function(event) {
	  
		event.preventDefault();    
		if ( s_pre.indexOf(';'+$('a.dish').attr("rel"))==-1){
        $.post(
            "/common/service/act_vote.cfm", { 
			voteid:$('a.ditch').attr("rel"),
			vote:'-1'
			
			},
			function(data){
				$.cookie('dcsrecipe_vote',s_pre +';'+ $('a.dish').attr("rel"));  
                refreshVote(); 
               	$.prompt(txtEm,{callback: mycallbackform, 
				submit: submitNewssub,
				buttons: { Submit:true }
				}); 
               
            }); 
			} else  $.prompt('You have already voted once before.');
   		 });
	
});
function refreshVote(){
	  if ($('a.ditch').attr("rel")) $.get(
            "/common/service/act_vote.cfm", { 
			voteid:$('a.ditch').attr("rel")
		
			
			},
			function(data){
				temp = data.split(';');

				 $('span.dish').html(temp[0]); 
				 $('span.dump').html(temp[1]);


                
                   
               
            });
    	 if ($.cookie('dcsrecipe_vote')==undefined)  s_pre=''; else  s_pre= $.cookie('dcsrecipe_vote');
		
		 if ( s_pre.indexOf(';'+$('a.dish').attr("rel")) > -1 ){$('div.dishit').hide();$('div.dishit-results').show(); }else {$('div.dishit-results').hide();$('div.dishit').show();}
	
}	

var txtEm = '<h2>Thanks for Voting!</h2><p>Be a guest at the DCS dinner table and receive our newsletter for fantastic recipes, cooking tips, and exclusive incentives.</p><div id="add-res"></div><form  id="newsletterFm" action=""><fieldset class="signup"><div class="form-row"><label for="newsletterFirstName">First Name:</label><input type="text" id="newsletterFirstName" /></div><div class="form-row"><label for="newsletterLastName">Last Name:</label><input type="text" id="newsletterLastName" /></div><div class="form-row"><label for="email">Email:</label><input type="text" id="newsletterEmail"/></div></fieldset></form>';

/*KITCHEN COLLECTION*/
function InitKC(){
	var currentString = null;
	$('#kc-subnav A, #kc-kitchen A').mouseenter(function(evt) {
         evt.preventDefault();
		currentString = $(this).attr("rel");
		switch (currentString) {
			 case "fridge":
						 $("#fridge-text").fadeIn('fast');
						 break ;
			case "dishdrawer":
						 $("#dishdrawer-text").fadeIn('fast');
						 break ;
			case "cooktop":
						 $("#cooktop-text").fadeIn('fast');
						 break ;
			case "ventilation":
						 $("#ventilation-text").fadeIn('fast');
						 break ;
			case "ranges":
						 $("#ranges-text").fadeIn('fast');
						 break ;
			case "ovens":
						 $("#ovens-text").fadeIn('fast');
						 break ;
		} 
    });
	
	$('#kc-subnav A, #kc-kitchen A').mouseleave(function(evt) {
         evt.preventDefault();
		$("#" + currentString + "-text").fadeOut('fast');
    });
}

/*NEW FEATURES SESION */
function InitFC(){
	var currentString = null;
	$('#fc-subnav A, #fc-kitchen A').mouseenter(function(evt) {
         evt.preventDefault();
		currentString = $(this).attr("rel");
		switch (currentString) {
			 case "fridge":
						 $("#fridge-text").fadeIn('fast');
						 break ;
			case "dishdrawer":
						 $("#dishdrawer-text").fadeIn('fast');
						 break ;
			case "cooktop":
						 $("#cooktop-text").fadeIn('fast');
						 break ;
			case "ventilation":
						 $("#ventilation-text").fadeIn('fast');
						 break ;
			case "ranges":
						 $("#ranges-text").fadeIn('fast');
						 break ;
			case "ovens":
						 $("#ovens-text").fadeIn('fast');
						 break ;
		} 
    });
	
	$('#fc-subnav A, #fc-kitchen A').mouseleave(function(evt) {
         evt.preventDefault();
		$("#" + currentString + "-text").fadeOut('fast');
    });
}

