var ajaxPagePath = FULL_DOMAIN_NAME + "umbraco/library.aspx";
var waitClass = ".wait";

jQuery(document).ready(function() {

    //css fix for join compaign module
    var elmJC = jQuery("div[id$='dvContainerJC']");
    if (elmJC.length > 0 && elmJC.hasClass("container-jc")) {
        if (jQuery.browser.msie) {
            elmJC.addClass("jc-ie");
        }
        else {
            elmJC.addClass("jc-ff");
        }
    }

    //css fix for join compaign module
    var elmJCRM = jQuery("h5.jsc-recipe-member-name");
    if (elmJCRM.length > 0) {
        if (jQuery.browser.msie) {
            elmJCRM.addClass("pd-top5");
        }
        else {
            elmJCRM.addClass("pd-top10");
        }
    }

    //apply pngfix
    jQuery(document).pngFix();

    //set rollovers
    setRollovers()

	//set selected navigation
    setRolloversTopMenu();
	
    //set selected navigation
    setSelectedNavigation();

    //set watermarks
    setWaterMarks()

    //set image upload control
    setRecipeImageUpload();
    setMemberImageUpload();

    //join campaign and send to friend
    joinCampaignToggle();
    sendToFriend();
    JoinCampaignHoverBg();

    //set maxlength
    setLengthRecipeIngredients();
    setLengthRecipeMethod();

    //implement ticker
//    wotnewsTicker();
    fastFactsTicker();

    //show delicious recipe tooltips
    deliciousRecipeTooltips();

    //filter articles
    filterArticle();

    //footer logo ticker
    footerTicker();

    //feature tile ticker
    featureTicker();
});

function setSelectedNavigation() {
    //$('ul.top-menu li.selected').corner("14px");
}

function setRolloversTopMenu() {
	jQuery("ul.top-menu").find("a").each(function() {
        jQuery(this).mouseover(function() {
            jQuery(this).parent().addClass("hover");
        });
        jQuery(this).mouseout(function() {
            jQuery(this).parent().removeClass("hover");
        });
    });
}


function joinCampaignToggle() {

    jQuery(".toggle-send-to-friend").click(function() {
        var mainSendToFriend = "div#sendToFriend";
        jQuery("div#joinCampaign").hide();
        jQuery(mainSendToFriend).show();
        jQuery(mainSendToFriend).find(".loader").hide();
        jQuery(mainSendToFriend).find("input[id$='imgSendToFriend']").show();
        return false;
    });

    jQuery(".toggle-join-campaign").click(function() {
        jQuery("div#joinCampaign").show();
        jQuery("div#sendToFriend").hide();
        return false;
    });

}

function joinCampaign() {
    try {
        var success = Page_ClientValidate('vgJoinCampaign');
        var dvJoinCampaign = jQuery("div#joinCampaign");
        if (success) {
            if (dvJoinCampaign != null) {

                var Name = dvJoinCampaign.find("input[id$='txtJCName']").val();
                var Email = dvJoinCampaign.find("input[id$='txtJCEmail']").val();

                var dataString = 'cm-name=' + Name + '&cm-iuithi-iuithi=' + Email;
                var dataURL = "http://email.pollen.com.au/t/r/s/iuithi/?" + dataString;
                document.location.href = dataURL;
                return false;
            }
        }
    } catch (e) {
        alert('Error in sending the request.\r\nPlease try again.');
        return false;
    }
    return false;
}

function sendToFriend() {
    jQuery("div#sendToFriend").find("input[id$='imgSendToFriend']").click(function() {
        var success = Page_ClientValidate('vgSendToFriend');
        var dvsendToFriend = jQuery("div#sendToFriend");
        if (success) {
            if (dvsendToFriend != null) {
                var YourEmail = dvsendToFriend.find("input[id$='txtYourEmail']").val();
                var FriendName = dvsendToFriend.find("input[id$='txtFriendsName']").val();
                var Email = dvsendToFriend.find("input[id$='txtFriendsEmail']").val();
                var SendUrl = window.location.toString();
                dvsendToFriend.find(".loader").show();
                var waitIcon = dvsendToFriend.find(".wait-icon");
                var message = dvsendToFriend.find(".loader-message");
                message.removeClass(".loader-success");
                message.removeClass(".loader-error");
                message.html('Sending..');
                waitIcon.show();
                jQuery(this).hide();
                $.post(ajaxPagePath, { action: "SendToFriend", yourEmail: YourEmail, friendName: FriendName, email: Email, sendUrl: SendUrl },
                function(data) {
                    if (data != 'false') {
                        waitIcon.hide();
                        message.addClass("loader-success");
                        message.html('Your email has been sent.');
                    }
                    else {
                        waitIcon.hide();
                        message.addClass("loader-error");
                        message.html('Your email could not be sent.');
                        jQuery("div#sendToFriend").find("input[id$='imgSendToFriend']").show();
                    }
                    waitIcon.hide();
                });
            }
        }
        return false;
    });
}

function JoinCampaignHoverBg() {
    $(".send-to-friend").hover(function() {
        $(this).parent().removeClass("toggle-bg").addClass("toggle-bg-green");
    });

    $(".send-to-friend").mouseout(function() {
        $(this).parent().removeClass("toggle-bg-green").addClass("toggle-bg");
    });

}

function setLengthRecipeIngredients() {
    var textareaId = 'txtIngredients';
    var maxLength = 1000;
    jQuery("textarea[id$='" + textareaId + "']").charCounter(maxLength, {
});
}

function setLengthRecipeMethod() {
    var textareaId = 'txtMethod';
    var maxLength = 2000;
    jQuery("textarea[id$='" + textareaId + "']").charCounter(maxLength, {
});
}

function wotnewsTicker() {
    $('ul#wotnews').innerfade({
        speed: 1000,
        animationtype: 'fade',
        timeout: 5500,
        type: 'sequence',
        containerheight: '130px',
        slide_timer_on: 'yes',
        slide_ui_text: 'wotnews',
        slide_ui_parent: 'wotnews',
        slide_nav_id: 'wotnews_nav'
    });
    $.setOptionsButtonEvent();


    $("#wotnewsNext").click(function() {
        $.next();
    });
    $("#wotnewsPrevious").click(function() {
        $.prev();
    });
}

var first = 0;
var speed = 1000;
var pause = 10500;
var partnerPause = 4000;
var featurePause = 8000;

function fastFactsTicker() {
    interval = setInterval(removeFirst, pause);
}

function removeFirst() {
    first = $('ul#fastfactsList li:first').html();
    $('ul#fastfactsList li:first')
			.animate({ opacity: 0 }, speed)
			.fadeOut('fast', function() { $(this).remove(); });
    addLast(first);
}

function addLast(first) {
    last = '<li style="display:none">' + first + '</li>';
    $('ul#fastfactsList').append(last)
    $('ul#fastfactsList li:last')
			.animate({ opacity: 1 }, speed)
			.fadeIn('slow');
}


var firstLi = 0;

function footerTicker() {
    interval = setInterval(removeFooterFirst, partnerPause);
}

function removeFooterFirst() {
    firstLi = $('ul#footerLogo li:first').html();
    $('ul#footerLogo li:first')
			.animate({ opacity: 0 }, speed)
			.fadeOut('fast', function() { $(this).remove(); });
    addFooterLast(firstLi);
}

function addFooterLast(firstLi) {
    lastLi = '<li style="display:none">' + firstLi + '</li>';
    $('ul#footerLogo').append(lastLi)
    $('ul#footerLogo li:last')
			.animate({ opacity: 1 }, speed)
			.fadeIn('slow');
}

function featureTicker() {
    interval = setInterval(removeFeatureFirst, featurePause);
}

function removeFeatureFirst() {
    firstLi = $('ul#featureTile li:first').html();
    $('ul#featureTile li:first')
			.animate({ opacity: 0 }, speed)
			.fadeOut('fast', function() { $(this).remove(); });
    addFeatureLast(firstLi);
}

function addFeatureLast(firstLi) {
    lastLi = '<li style="display:none">' + firstLi + '</li>';
    $('ul#featureTile').append(lastLi)
    $('ul#featureTile li:last')
			.animate({ opacity: 1 }, speed)
			.fadeIn('slow');
}

function deliciousRecipeTooltips() {
    var elm = $('div#recipeImgHover');
    var elm_ul = $("ul.home-deliciousrecipe-list");
    
    if (elm_ul.length == 0)
        return;
        
    if (elm.length == 0)
        return;

    $().mousemove(function(e) {
        var ul_x1 = $(elm_ul).offset().left;
        var ul_y1 = $(elm_ul).offset().top;
        var ul_x2 = ul_x1 + $(elm_ul).width();
        var ul_y2 = ul_y1 + $(elm_ul).height();
    
        var elm2_x = e.pageX;
        var elm2_y = e.pageY;
        if (ul_x1 <= elm2_x && ul_x2 >= elm2_x && ul_y1 <= elm2_y && ul_y2 >= elm2_y) {
            if ($(e.target).is('ul')) {
                normalModeDeliciousRecipe();
            }
        }
        else {
            normalModeDeliciousRecipe();
        }
    });

    $('a.delicious-tooltip').hover(function() {
        var rURL = $(this).attr("href");
        var x = $(this).parent().offset().left;
        var y = $(this).parent().offset().top;
        $(elm).css("cursor", "pointer");
        $(elm).css("position", "absolute");
        $(elm).css("display", "block");
        $(elm).css("left", x);
        $(elm).css("top", y);
        $(elm).click(function() {
            document.location.href = rURL;
        });

        active_tooltip = $(this).attr("rel");
        $("div[id^='hdDelicious']").hide();
        $("div[id$='hdDelicious" + active_tooltip + "']").show();
        $("div#divDeliciousNormal").hide();
    },
	function(e) {
	    var elm_x = $(elm).offset().left;
	    var elm_y = $(elm).offset().top;
	    var x = $(this).parent().offset().left;
	    var y = $(this).parent().offset().top;
	    if (elm_x != x && elm_y != y) {
	        $(elm).css("display", "none");
	        $("div#divDeliciousNormal").show();
	        $("div[id$='hdDelicious" + active_tooltip + "']").hide();
	    }
	});

    $("input#search-delicious").watermark("Search for more recipes");
    $("input#search-delicious").css("water-mark-text");
}

function normalModeDeliciousRecipe() {
    var elm = $('div#recipeImgHover');   
    $("div[id^='hdDelicious']").hide();
    $("div#divDeliciousNormal").show();
    $(elm).css("display", "none");
}

function enterKeyPress(e) { //e is event object passed from function invocation
    var characterCode //literal character code will be stored in this variable

    if (e && e.which) { //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which; //character code is contained in NN4's which property
    }
    else {
        e = event
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }

    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        searchRecipe(); //submit the form
        return false;
    }
    else {
        return true;
    }
}

function searchRecipe() {
    var searchTerm = urlEncode(document.getElementById('search-delicious').value);
    if (searchTerm.length > 0)
        document.location.href = "/recipes.aspx?search=" + searchTerm;
    else
        alert("Please enter search keywords.");
}

function setRecipeImageUpload() {
    jQuery("input:file[id$='fuRecipePhoto']").filestyle({
        image: FULL_DOMAIN_NAME + "images/btn-browse.gif",
        imageheight: 27,
        imagewidth: 86,
        width: 250
    });
}

function setMemberImageUpload() {
    jQuery("input:file[id$='fuMemberPhoto']").filestyle({
        image: FULL_DOMAIN_NAME + "images/btn-browse.gif",
        imageheight: 27,
        imagewidth: 86,
        width: 250
    });
}

function filterArticle() {
    var filterClass = ".filterBy";
    var filterText = "recordFilter";
    jQuery(filterClass).change(function() {
        var filter = jQuery(this).find('option').filter(':selected').text();
        var filterVal = jQuery(this).find('option').filter(':selected').val();
        if (filterVal != '0') {
            var loc = window.location.toString();

            if (getQuerystring("filterby", "") != "" || getQuerystring("page", "") != "") {
                loc = loc.replace("&" + filterText + "=" + filter, '') + "&" + filterText + "=" + filter;
            }
            else {
                loc = loc.replace("?" + filterText + "=" + filter, '') + "?" + filterText + "=" + filter;
            }
            window.location = loc;
        }
    });

    if ("date" == getQuerystring(filterText, "")) {
        jQuery(filterClass).val("Date");
    }
    if ("name" == getQuerystring(filterText, "")) {
        jQuery(filterClass).val("Name");
    }
}

function setWaterMarks() {
    $("input[id$='txtJCName']").watermark("Your name");
    $("input[id$='txtJCName']").css("water-mark-text");

    $("input[id$='txtJCEmail']").watermark("Your email");
    $("input[id$='txtJCEmail']").css("water-mark-text");

    $("input[id$='txtYourEmail']").watermark("Your email");
    $("input[id$='txtYourEmail']").css("water-mark-text");


    $("input[id$='txtFriendsName']").watermark("Your friends name");
    $("input[id$='txtFriendsName']").css("water-mark-text");

    $("input[id$='txtFriendsEmail']").watermark("Your friends email");
    $("input[id$='txtFriendsEmail']").css("water-mark-text");
}

function setRollovers() {
    //homepage rollovers
    jQuery("#mainLeft").find("div.grid-item-details-home").each(function() {
        jQuery(this).mouseover(function() {
            jQuery(this).animate({ opacity: 1 }, 1)
            .fadeOut(0, function() {
                jQuery("#mainLeft").find("div.grid-item-hover-home").each(function() {
                    if (jQuery(this).css("display") == 'block') {
                        jQuery(this).hide();
                    }
                });
                jQuery(this).parent().find("div.grid-item-hover-home").show();
            });
        });
    });

    jQuery("#mainLeft").find("div.grid-item-hover-home").each(function() {
        jQuery(this).mouseleave(function() {
            jQuery(this).animate({ opacity: 1 }, 1)
            .fadeOut(0, function() {
                jQuery("#mainLeft").find("div.grid-item-details-home").each(function() {
                    if (jQuery(this).css("display") == 'none') {
                        jQuery(this).show();
                    }
                });
            });
        });
    });

    jQuery("#mainLeft").find("div.list-item-bg").each(function() {
        jQuery(this).mouseover(function() {
            jQuery(this).addClass("list-item-bg-hover");
        });
        jQuery(this).mouseout(function() {
            jQuery(this).removeClass("list-item-bg-hover");
        });
    });

    //landing page rollovers
    jQuery("#mainLeft").find("div.grid-item-details").each(function() {
        jQuery(this).mouseover(function() {
            jQuery(this).animate({ opacity: 1 }, 1)
            .fadeOut(0, function() {
                jQuery("#mainLeft").find("div.grid-item-hover").each(function() {
                    if (jQuery(this).css("display") == 'block') {
                        jQuery(this).hide();
                    }
                });
                jQuery(this).parent().find("div.grid-item-hover").show();
            });
        });
    });

    jQuery("#mainLeft").find("div.grid-item-hover").each(function() {
        jQuery(this).mouseleave(function() {
            jQuery(this).animate({ opacity: 1 }, 1)
            .fadeOut(0, function() {
                jQuery("#mainLeft").find("div.grid-item-details").each(function() {
                    if (jQuery(this).css("display") == 'none') {
                        jQuery(this).show();
                    }
                });
            });
        });
    });

    jQuery("#mainLeft").find("div.list-item-bg").each(function() {
        jQuery(this).mouseover(function() {
            jQuery(this).addClass("list-item-bg-hover");
        });
        jQuery(this).mouseout(function() {
            jQuery(this).removeClass("list-item-bg-hover");
        });
    });



}
