﻿var CatChow = {};
CatChow.Constants = {};

// Constants
CatChow.Constants.CATEGORIES = {};
CatChow.Constants.CATEGORIES.BOTH = 0;
CatChow.Constants.CATEGORIES.CAT = 1;
CatChow.Constants.CATEGORIES.KITTEN = 2;

CatChow.Constants.SLIDER_TEXT = {};
CatChow.Constants.SLIDER_TEXT.CAT_ADVICE = ['', 'Cat Care', 'Watch Videos', 'Ask a Mentor', 'Cat Care']; // note empty [0] in array
CatChow.Constants.SLIDER_TEXT.KITTEN_ADVICE = ['', 'Kitten Care', 'Watch Videos', 'Ask a Mentor', 'Kitten Care']; // Note that element [1] repeats at end
CatChow.Constants.SLIDER_TEXT.WELL_BEING = ['', 'Enhancing Well-Being', 'Connected for the Cause<sup>&trade;</sup>', 'Housecat Housecall<sup>&reg;</sup>', 'Enhancing Well-Being'];

CatChow.Constants.EXT_SEARCH = {};
CatChow.Constants.EXT_SEARCH.ERROR_TEXT = "Please Enter a Search Term";
CatChow.Constants.EXT_SEARCH.VENDOR_URL = "http://search.atomz.com/search/?sp_a=sp10033d5f&sp_t=catchow&sp_k=Cat%20Chow&sp_p=all%20&sp_f=ISO-8859-1&sp_q=";


//
// Run Global Methods
// ----------------------------------------------------------

$(document).ready(function() {

    CatChow.commentToggle();
    CatChow.dropDown();
    CatChow.pop();
    CatChow.ext();
    CatChow.popShare();
    CatChow.print();
    CatChow.revealToggle(".facts", "div");
    CatChow.revealToggle(".questions", ".answer");
    if(typeof window.CatChow.setupSliders == 'function') {
        CatChow.setupSliders();
    }
    
    CatChow.sameLine("Purina<sup>®</sup> Cat Chow<sup>®</sup>");
    CatChow.sameLine("Housecat Housecall<sup>®</sup>");
    CatChow.sameLine("Susan G. Komen for the Cure<sup>®</sup>");
    CatChow.sameLine("Susan G. Komen<sup>®</sup>");
    CatChow.submitSearch();
    CatChow.sideSubmitSearch();
    CatChow.searchError();
    CatChow.errorStyle();

    $("#footer .text-input").smartInput();
    $(".feat-qa").listbrowser();
    $("body.mentor .quotes").listbrowser();
    $("body.mentor-landing .quotes").listbrowser();
    $(".comments textarea").characterCount();
    $(".ask textarea").characterCount();
    $(".content-tabs").catChowBagTabs();
    
    $(".comments .textarea-input").maxLength(500);
    $(".ask .textarea-input").maxLength(500);

    $(".product-landing .related-articles ul li a").truncate(50, {
        chars: /\s/,
        trail: ["&hellip;", "&hellip;"]
    });

});


//
// CatChow Methods
// ----------------------------------------------------------

CatChow.dropDown = function() {
    // backup drop down functionality for IE6
    var $container = $(".drop");
    var $links = $("ul", $container);

    $container.hover(
		function() {
		    if ($("body.care").length == 0) {
		        $links.show();
		        $(this).addClass("hover");
		        $(this).css("background-repeat", "repeat");
		    }
		},
		function() {
		    if ($("body.care").length == 0) {
		        $links.hide();
		        $(this).removeClass("hover");
		        $(this).css("background-repeat", "no-repeat");
		    }
		}
	);
};

CatChow.commentToggle = function(){
    var $comments = $(".comments blockquote"),
        $toggle = $(".comment-toggle");
    
    if( $comments.length <= 1 ){
        $toggle.hide();
    }
    
    $comments.each(function(){
        $(".comments blockquote:gt(0)").hide();
    });
    
    $toggle.toggle(function(e){
        e.preventDefault();
        $(this).removeClass("show").addClass("hide").html("Hide Comments");
        $(".comments blockquote").slideDown("slow");
    },function(e){
        e.preventDefault();
        $(this).removeClass("hide").addClass("show").html("Show All Comments");
        $(".comments blockquote:gt(0)").slideUp("slow");
    });
};

// Fact toggle - pass selector for container. hash(#) href associates to <p> "id"
CatChow.revealToggle = function(container,hide){
    var $facts = $(container),
        $toggles = $("a", $facts),
        $content = $(hide, $facts),
        target;
        
    $content.each(function(){ 
        $(this).hide();
    });
    
    $toggles.toggle(function(e){
        e.preventDefault();
        target = $(this).attr("href").toString().split("#");
        target = "#" + target[1];
        $(this).html("Hide").addClass("reveal-hide");
        $(target).slideDown("fast");
    },function(e){
        e.preventDefault();
        target = $(this).attr("href").toString().split("#");
        target = "#" + target[1];
        $(this).html("Show").removeClass("reveal-hide");
        $(target).slideUp("fast");
    });
};

CatChow.pop = function(){
    $('a.pop').click(function(e){
        e.preventDefault();
        window.open(this.href,"legal",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,top=(20),left=(20),screenX=(20),screenY=(20),width=660,height=450');
        return false;
    });
};

CatChow.popShare = function(){
    $('a.pop-share').click(function(e){
        e.preventDefault();
        window.open(this.href,"Share",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,top=(20),left=(20),screenX=(20),screenY=(20),width=410,height=640');
        return false;
    });
};

CatChow.print = function() {
    $(".print a").click(function() {
        window.print();
        return false;
    });
};

CatChow.setupSliders = function() {
	var classes = $('body').attr('class').split(' ');
	var page;
	jQuery.each(classes, function() {
		if (this == 'kitten-advice' || this == 'cat-advice' || this == 'well-being') {
			page = this.replace("-", '_').toUpperCase();
		}
	});
	
    $('body.care .anythingSlider, body.well-being .anythingSlider').anythingSlider({
 		// NOTE - was easeInOutExpo in initial prototype
         easing: "easeInOutCubic",        // Anything other than "linear" or "swing" requires the easing plugin
         autoPlay: false,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
         delay: 3000,                    // How long between slide transitions in AutoPlay mode
         startStopped: false,            // If autoPlay is on, this can force it to start stopped
         animationTime: 900,             // How long the slide transition takes
         hashTags: true,                 // Should links change the hashtag in the URL?
         buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
         pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
         startText: "Go",             // Start text
         navigationFormatter: function(index, panel) {
             var currentPane = $(panel).attr("rel");
             return currentPane;
         },
         navload: function() {
			var nextPage = this.currentPage + 1;
			var nextText = CatChow.Constants.SLIDER_TEXT[page][nextPage];
 			$(".anythingSliderTitle strong").html(nextText);
 		},
 		swap: function(){
			var nextPage = this.currentPage + 1;
			var nextText = CatChow.Constants.SLIDER_TEXT[page][nextPage];
 			$(".anythingSliderTitle strong").html(nextText);
 			
 			// Force video stop on swap
 			var $videos = $(".anythingSlider object");
 			$videos.each(function(){
		        var $videoParent = $(this).parent();
		        var vidMarkUp = $videoParent.html();
		        console.log("videoParent : ",$videoParent);
		        console.log("vidMarkUp : ",vidMarkUp);
		        console.log("this : ",this);
		        console.log("$(this) : ",$(this));
		        $videoParent.html("");
		        $videoParent.html(vidMarkUp);
 			});
 		}
     });
};

// Footer Search
// client side to avoid conflicting postback validation with server side controls
CatChow.submitSearch = function () {
    var $search = $("#FooterSearch"),
        $submit = $(".footer-search a"),
        $form = $("form"),
        defaultVal = $search.val(),
        currentVal,
        url;
    
    $submit.click(function(e){
        e.preventDefault();
        currentVal = $search.val();
        if (currentVal != defaultVal && currentVal != CatChow.Constants.EXT_SEARCH.ERROR_TEXT && currentVal != "") {
            url = CatChow.Constants.EXT_SEARCH.VENDOR_URL + currentVal;
            window.open(url, "searchResults", "");
        }else{
            $search.attr("value", CatChow.Constants.EXT_SEARCH.ERROR_TEXT).addClass("error");
        }
    });
    
    // enter key fix for footer search
    $search.focus(function(e){
        $(this).keypress(function(e){
            if(e.which == 13){
                e.preventDefault();
                $submit.click();
            }
        });
    });

    $search.focus(function(){
        $(this).removeClass("error");
    });
};


CatChow.sideSubmitSearch = function () {
    // enter key fix for sidebar search
    var $search = $(".aside .search_cat_care"),
        $submit = $(".aside .search-box .button"),
        $form = $("form");

    $search.focus(function(e){
        $(this).keypress(function(e){
            if(e.which == 13){
                e.preventDefault();
                $submit.click();
            }
        });
    });

};

CatChow.searchError = function (){
    var $error = $(".search-error");
        
    if($error.length > 0){
        var eTxtLength = $error.html().length;
    }
        
    if(eTxtLength > 3){
        $(window).scrollTo( '.search-error', 900, {offset:{left:0,top:-200}} );
    }
};

CatChow.errorStyle = function(){
    // detect user question or comment errors and apply styles to astersks by labels
    try {
        var errorOutput = $(".error-summary div").html().toString(),
            errorOutputAlt = $(".error-summary span").html().toString(),
            errors = errorOutput + errorOutputAlt;
    
        //alert("there are errors!");
        
    }
    catch(err) {
        // prevent js error if .html() is null
        return false;
    }
    
    // todo add classes to style asterisks red
    /*
    $(".comments .e").addClass("e-style"); // didnt work
    $(".ask .e").addClass("e-style"); // works
    */
};

//
// Utility Functions
// ----------------------------------------------------------

CatChow.ext = function(){
    $('a.ext').click(function(){
        window.open(this.href);
        return false;
    });
    
    /*
    $(".promo-landing a:not(.int):not(.pop)").click(function(e){
        e.preventDefault();
        window.open(this.href);
        return false;
    });
    */
};

// ensure trade names are on one line
CatChow.sameLine = function(txt) {
    var re = new RegExp(txt, "gi");
    var openTxt = '<span class="nobr">';
    var closeTxt = '</span>';
    $("p").each(function() {
        $(this).html($(this).html().replace(re, openTxt + txt + closeTxt));
    });
};


// silences console commands in browsers without firebug
if (!window.console || !console.firebug) {
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
	"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

	window.console = {};
	for (var i = 0; i < names.length; ++i)
		window.console[names[i]] = function() {};
}

