/* Project Name Global Javascript Functions

By  Christoph Saxe and Will Moore - ISITE Design


*/

//start the jQuery functions
$(document).ready(function() {
    /*apply automatic input clearing to the search input - add as needed*/
    $("#sitesearch input").inputClear();

    // alternate version of the above plugin that pulls the label, sets as default value and hides it
    $("#searchform input").inputSetter();


    // add class to drop downs and buttons for IE <6
    if (document.all) {
        $("#nav li, button").hover(
	            function() {
	                $(this).addClass("over");
	            },
	            function() {
	                $(this).removeClass("over");
	            }
	    );
    } // if document.all


    //home page only
    if ($('body.home').length > 0) {
        $('.listing-category li:nth-child(3n)').addClass('third');
        // flash replacement on h1
        var params = { allowScriptAccess: "sameDomain", allowFullScreen: "false", quality: "high", bgcolor: "#ffffff" };
        var flashvars = { gallery_xml: "/Marketing/HomePageFlashFeed.ashx" };
        swfobject.embedSWF("/_resources/flash/gallery_green.swf", "flashreplace", "640", "300", "9.0.0", "/_resources/flash/expressInstall.swf", flashvars, params, false);
    }

    //lists - add .last to all lists
    $("ul, ol").find("li:last").addClass('last');
    // 'by name' section layout classing
    $("ul.letters").find("li:nth-child(7n)").addClass('dp_no-right-margin');

    //.last addition features within sections
    $(".section .feature:last").addClass('last');

    //tables - add "even" class to alternate rows on all tables.
    $("table tbody").find("tr:even").addClass("even");

    //hey, let's stripe some comments. k?
    if ($('.commentswrap').length > 0) {
        $(".blog-comments li:odd").addClass("odd");
    }

    // tabbed content
    if ($('.tabs li').length > 0) {
        $('.tabs').tabs();
    }

    // star-ratings
    // $cancel.remove();
    if ($('.rating-wrap').length > 0) {
        $('.rating-wrap').stars({
            inputType: "select",
            selected: 0
            //_disableCancel: true,
        });
    }

    // availability widget - for product details page.
    $('.availability').availabilityWidget();

    // FAQ toggler
    $(".faqtopics dt").click(function() {
        $(this).next().slideToggle(200);
    }).next().hide();

    if ($(".tablesorter").length > 0) {
        $(".tablesorter").tablesorter()
    }

    // hidden submit buttons
    $('button.hidden').hide();

    // external links
    $("a[rel=external], a[href^=http://]:not(a[href*=www.melissas.com])").click(function() { window.open(this.href); return false; });

    $("a.tooltip").tooltip({showURL: false});

    //send to friend link
    $("a.email-link").click(function() {
        //alert('yup');
        window.open(this.href, "emaillink", "height=600, width=500, location=0, menubar=0, status=0");
        return false;
    });
    


    // ie6+7 : browse recipes lists
    if (document.all) {
        $('.recipes.landing #primary .browse .column li:not(.last)').each(function() {
            var content = $(this).html() + '<img src="/_resources/img/css/bullet-recipes.gif" alt="decorative bullet image" />';
            $(this).html(content);
        });
    }
    
    $('.backlink').find('a').click(function(){ history.go(-1); });

    // store locator support
    $("#storeLocator").change(function() {
        $("#storeLocatorProgress").toggle();
        $("#stores").html("");
        $.getJSON("/Marketing/StoreLocatorData.ashx?state=" + $(this).val(), function(reply) {
            $("#storeLocatorProgress").toggle();

            var list = '<ul class="dp_listing">';
            for (var i = 0; i < reply.length; i++) {
                list += "<li>" + reply[i].Title + "</li>";
            }

            list += "</ul>";

            $("#stores").html(list);
        });
    });

}); // document ready / end jquery functions

/* clear search field on click - made into plugin so it can easily be used more than once. */
jQuery.fn.inputClear = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};

// alternate version of the above. pull label and insert as field. clear with click.
jQuery.fn.inputSetter = function() {
	
	return this.each(function() {
	
		var $input = $(this);
		var $label = $("label[for='"+$input.attr("id")+"']");
		var labeltext = $label.text();
		
		$label.hide();
		$input.val(labeltext);
		
		$input.focus(function() {
			if (this.value == labeltext) {
				this.value = "";
			}
		}).blur(function() {
			if (!this.value.length) {
				this.value = labeltext;
			}
		});
		
	});
};

jQuery.fn.availabilityWidget = function(){
    return this.each(function(){
        var $parent = $(this);
        var $filter = $parent.find('ul.filter');
        var $charts = $parent.find('dl');
        
        $parent.find('h4').each(function(){$(this).replaceWith('<label for="origin">'+$(this).text()+'</label>')});
        $filter.children('li').each(function(){
            var $li = $(this);
            var $a = $(this).children('a');
            $li.replaceWith('<option value="'+$a.attr('href').substr(1)+'">'+$a.text()+'&nbsp;</option>');
        });
        $filter.replaceWith('<select id="origin">'+$filter.html()+'</select>');
        
        $('#origin').change(function(){
            var target = "#"+$(this).attr('value');
            $charts.hide().end().find(target).show();
        });
        
        $charts.find('dt')
        .each(function(){ var month = $(this).text();
            $(this).attr('title', month);
            $(this).text(month.substr(0,3));
        });
        
        $charts.find('dd')
        .each(function(){ 
            $(this).addClass($(this).text().toLowerCase());
            $(this).tooltip({ bodyHandler: function() { 
                                            return "Availability for <strong>"+$(this).prev('dt').attr('title')+"</strong> is <strong>"+$(this).text()+"</strong>"; 
                                        },
                                        track: true,
                                        top:0
                             });
        });
        $charts.not(':first').hide();
        $parent.removeClass('availability').addClass('availability-graph');
    });
};



// custom validation method for jquery.validation.js. use with inputSetter to validate fields as required but not equal to the label (default value)
// may need to change where to look for the label depending on particular html
/*
jQuery.validator.addMethod("notEqualTo", function(value, element, param) {
	return $(element).val()!=$(element).prev("label").text();
}, "error");
*/

function toggleBlogComments(targetElement, result)
{
    var target = $(targetElement);
    if(target.html() == "") 
    {
        target.hide().html(result);
        $(".blog-comments li:odd", target).addClass("odd");
        target.show("medium");
    }
    else target.hide("fast").html("");
}

function toggleVisibility(){ if(document.all) $('.toggler').toggle(); }

// clean console.log
function cl(logit){ if(window.console&&window.console.firebug) { console.log(logit) } };//cl()
