$(document).ready(function() {
    Recipes.init();
});

var Recipes = {
    init: function()
    {
        var ratings = $('ul.ratings');
        if (ratings) Recipes.Ratings.init(ratings); // configure ratings functionality

        var printLink = $('#utilities #print');
        if (printLink) Recipes.Print.init(printLink); // configure print link

    //  var o = $("#divToPrint");
    //    o.jqprint();


        var emailUpdates = $('#email-updates');
        if (emailUpdates) Recipes.EmailUpdates.init(emailUpdates); // configure e-mail updates form validation

        try
        {   // set the rating stars
            var setToStatic=true;
            var cookieValue = getCookie('emend-recipe');
            if (cookieValue == null)
            {
                setToStatic=false;
            }
            else
            {
                var xx = cookieValue.search(theRecipeId+'::');
                if (xx >= 0)
                {
                    setToStatic=true;
                }
                else
                {
                    setToStatic=false;
                }
            }

            if (setToStatic)
            {
                setStarsToStatic();
            }
        }
        catch (exception) {}
    }
};

Recipes.Ratings = {
    init: function(containers)
    {
        this.containers = containers;

        // set up methods
        this.attachEvents();
    },

    // attach mouse events to ratings container
    attachEvents: function()
    {
        this.containers.bind('mouseover', this.onMouseOver).bind('mouseout', this.onMouseOut).bind('click', this.onClick);
    },

    // mouseover events
    onMouseOver: function(event)
    {
        var currentRating = $(this).attr('class').split(' ')[1]; // get current rating from container (this) class list
        $(this).data('currentRating', currentRating); // store rating data on container for future use

        var target = event.target;
        var href = $(target).find('a').get(0); // get href
        if (href == null) return;

        if (currentRating) $(this).removeClass(currentRating); // remove old "current" rating class
        $(this).addClass(target.className); // show container with "new" moused over rating
    },

    // mouseout events
    onMouseOut: function(event)
    {
        var currentRating = $(this).data('currentRating'); // retrieve current rating

        $(this).removeClass(); // removed "new" moused over rating
        $(this).addClass('ratings');
        if (currentRating) $(this).addClass(currentRating); // add old "current" rating class
    },

    // click events
    onClick: function(event)
    {
        var target = event.target;
        if ($(target).find('a').get(0))
        {
            // TODO: add functionality for setting ratings
           // console.log($(target).find('a').attr('href').substr(1));
        }
    }
};

Recipes.EmailUpdates = {
    _requiredMsg: 'This field is required.',
    _emailMsg: 'Please provide a correct e-mail address in this format: email@addresss.com',
    _zipMsg: 'Please provide a correct ZIP code in this format: 12345',
    _enabledBtn: '<img alt="Finish" src="/emend/consumer/images/tools/recipes/button-finish.gif" width="65" height="23" />',
    _disabledBtn: '<img alt="Finish" src="/emend/consumer/images/tools/recipes/button-finish-off.gif" width="65" height="23" />',

    init: function()
    {
        this.container = $('#main'); // need to reference shadowbox container which copies hardcoded form
        this.fieldsToValidate = new Array("email", "firstname", "lastname", "postalcode");

        // set up methods
        this.buildCache();
        this.attachEvents();
        this.updateButton();
    },

    // cache elements for faster reference
    buildCache: function()
    {
        this.email = this.container.find('input[name=email]');
        this.firstName = this.container.find('input[name=firstname]');
        this.lastName = this.container.find('input[name=lastname]');
        this.zipCode = this.container.find('input[name=postalcode]');
        this.button = this.container.find('button');

        this.email.data('thisClass', this);
        this.firstName.data('thisClass', this);
        this.lastName.data('thisClass', this);
        this.zipCode.data('thisClass', this);
        this.button.data('thisClass', this);
    },

    // attach mouse events to email signup items
    attachEvents: function()
    {
        this.email.bind('blur', this.onFieldBlur);
        this.firstName.bind('blur', this.onFieldBlur);
        this.lastName.bind('blur', this.onFieldBlur);
        this.zipCode.bind('blur', this.onFieldBlur);
        this.button.bind('click', this.onButtonClick);
    },

    updateButton: function()
    {
        var validFields = this.container.find('input.valid');
        if (validFields.length == this.container.find('input.required').length)
        {
            this.button.html(this._enabledBtn);
            this.button.removeClass().addClass('enabled');
            this.button.disabled = false;
            return;
        }
        this.button.html(this._disabledBtn);
        this.button.removeClass().addClass('disabled');
        this.button.disabled = true;
    },

    onFieldBlur: function(event)
    {
        var item = $(this);
        var thisClass = item.data('thisClass');

        if (item.hasClass('required')) thisClass.validate(item, thisClass._requiredMsg, function(field) { return (field.val() == ''); });
        if (item.hasClass('postalcode')) thisClass.validate(item, thisClass._zipMsg, function(field) { var reZip = /^\d{5}(-\d{4})?$/; return (field.val().match(reZip) == null); });
        if (item.hasClass('email')) thisClass.validate(item, thisClass._emailMsg, function(field) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return (field.val().match(re) == null); });

        thisClass.updateButton();
    },

    validate: function(field, msg, test)
    {
        var container = field.parent('div');

        if (test(field))
        {
            field.removeClass('valid').addClass('error').addClass('invalid');
     //       this.addErrorMessage(container, msg);
            return;
        }

        field.removeClass('error').removeClass('invalid').addClass('valid');
        this.removeErrorMessage(container);
    },

    addErrorMessage: function(container, msg)
    {
        var errorContainer = container.find('p.error');
        if (errorContainer.size() == 0)
        {
            container.append('<p class="error">'+msg+'</p>');
            return;
        }
        errorContainer.html(msg);
    },

    removeErrorMessage: function(container)
    {
        var errorContainer = container.find('p.error');
        errorContainer.remove();
    },

    onButtonClick: function(event)
    {
        var container = $('#main form');
        if (container.find('input.invalid').length == 0)
        {
            container.submit();
        }
        else
        {
            return false;
        }
    }
};

Recipes.EmailSignup = {
    _requiredMsg: 'This field is required.',
    _emailMsg: 'Please provide a correct e-mail address in this format: email@addresss.com',
    _enabledBtn: '<img alt="Send" src="/emend/consumer/images/tools/recipes/button-send.gif" width="60" height="23" />',
    _disabledBtn: '<img alt="Send" src="/emend/consumer/images/tools/recipes/button-send-off.gif" width="60" height="23" />',

    init: function()
    {
        this.container = $('#shadowbox_content'); // need to reference shadowbox container which copies hardcoded form

        // set up methods
        this.buildCache();
        this.attachEvents();
//        this.updateButton();
    },

    // cache elements for faster reference
    buildCache: function()
    {
        this.emailFormScreen = this.container.find('div#email-form');
        this.form = this.container.find('form');
        this.friendsEmail = this.container.find('input[name=toEmail]');
        this.userName = this.container.find('input[name=firstname]');
        this.userEmail = this.container.find('input[name=fromEmail]');
        this.button = this.container.find('button');
        this.thankYouScreen = this.container.find('div#thank-you');
        this.returnLink = this.thankYouScreen.find('a');
        this.errorScreen = this.container.find('div#error');
        this.recipeTitle = $('img#recipe-hdr').attr('alt');

        this.form.data('thisClass', this);
        this.friendsEmail.data('thisClass', this);
        this.userName.data('thisClass', this);
        this.userEmail.data('thisClass', this);
        this.returnLink.data('thisClass', this);
    },

    // attach mouse events to email signup items
    attachEvents: function()
    {
        this.form.bind('submit', this.onFormSubmit);
//        this.friendsEmail.bind('blur', this.onFieldBlur);
//        this.userName.bind('blur', this.onFieldBlur);
//        this.userEmail.bind('blur', this.onFieldBlur);
        this.returnLink.bind('click', this.onReturnClick);
    },

    updateButton: function()
    {
        var validFields = this.container.find('input.valid');
        if (validFields.length == this.container.find('input.required').length)
        {
            this.button.html(this._enabledBtn);
            this.button.removeClass().addClass('enabled');
            this.button.disabled = false;
        }
        else
        {
            this.button.html(this._disabledBtn);
            this.button.removeClass().addClass('disabled');
            this.button.disabled = true;
        }
        return;
    },

    onFieldBlur: function(event)
    {
        var item = $(this);
        var thisClass = item.data('thisClass');

        if (item.hasClass('required')) thisClass.validate(item, thisClass._requiredMsg, function(field) { return (field.val() == ''); });
        if (item.hasClass('email')) thisClass.validate(item, thisClass._emailMsg, function(field) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return (field.val().match(re) == null); });

        thisClass.updateButton();
    },

    validate: function(field, msg, test)
    {
        var container = field.parent('li');

        if (test(field))
        {
            field.removeClass('valid').addClass('error').addClass('invalid');
            this.addErrorMessage(container, msg);
            return false;
        }

        field.removeClass('error').removeClass('invalid').addClass('valid');
        this.removeErrorMessage(container);
        return true;
    },

    addErrorMessage: function(container, msg)
    {
        var errorContainer = container.find('p.error');
        if (errorContainer.size() == 0)
        {
            container.prepend('<p class="error">'+msg+'</p>');
            return;
        }
        errorContainer.html(msg);
    },

    removeErrorMessage: function(container)
    {
        var errorContainer = container.find('p.error');
        errorContainer.remove();
    },

    onFormSubmit: function(event)
    {
        var item = $(this);
        var thisClass = item.data('thisClass');

        var rc1 = thisClass.validate(thisClass.friendsEmail, thisClass._requiredMsg, function(field) { return (field.val() == ''); });
        if (rc1)
        {
            rc1 = thisClass.validate(thisClass.friendsEmail, thisClass._emailMsg, function(field) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return (field.val().match(re) == null); });
        }
        var rc2 = thisClass.validate(thisClass.userEmail, thisClass._requiredMsg, function(field) { return (field.val() == ''); });
        if (rc2)
        {
          rc2 =  thisClass.validate(thisClass.userEmail, thisClass._emailMsg, function(field) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return (field.val().match(re) == null); });
        }
        var rc3 = thisClass.validate(thisClass.userName, thisClass._requiredMsg, function(field) { return (field.val() == ''); });

        if ((!rc1) || (!rc2) || (!rc3))
        {
            return false;
        }
        if ((rc1) && (rc2) && (rc3))
        {
            emailRecipeToFriend(this);
        }

        // make ajax call
        // "on success" hide #email-form, show #thank-you
        // "on error" hide #email-form, show #error
     //   emailRecipeToFriend(this);

        return false; // prevent default form submit
    },

    showEmailFormScreen: function()
    {
        this.thankYouScreen.hide(); // hide thank you screen
        this.errorScreen.hide(); // hide thank you screen
        this.emailFormScreen.show(); // show email form screen
    },

    showThankYouScreen: function()
    {
        this.emailFormScreen.hide(); // hide email form screen
        this.thankYouScreen.find('h4').text('"'+this.recipeTitle+'" Recipe sent!'); // update thank you title
        this.thankYouScreen.show(); // show thank you screen
    },

    showErrorScreen: function()
    {
        this.emailFormScreen.hide(); // hide email form screen
        this.errorScreen.show(); // show thank you screen
    },

    onReturnClick: function(event)
    {
        var item = $(this);
        var thisClass = item.data('thisClass');

        thisClass.friendsEmail.val(''); // reset Friend's email field
        thisClass.showEmailFormScreen();

        return false; // prevent default click
    }
};

Recipes.Print = {
    init: function(printLink)
    {
        this.printLink = printLink;

        this.attachEvents();
    },

    // attach mouse events to print link
    attachEvents: function()
    {
        this.printLink.bind('click', this.onClick);
    },

    // click events
    onClick: function(event)
    {
        event.preventDefault();
        window.print();
    }
}


function rateRecipe(recipeId,rating,action)
{
    var ajaxObject = null;
    if(window.XMLHttpRequest)
    {
        ajaxObject = new XMLHttpRequest();
    }
    else if(new ActiveXObject('Msxml2.XMLHTTP'))
    {
        ajaxObject = new ActiveXObject('Msxml2.XMLHTTP');
    }
    else if(new ActiveXObject('Microsoft.XMLHTTP'))
    {
        ajaxObject = new ActiveXObject('Microsoft.XMLHTTP');
    }

    ajaxObject.open("GET", "/aprepitant/"+action, true);
    ajaxObject.onreadystatechange = function() {
        if(ajaxObject.readyState==4) {
            displayResults(ajaxObject.responseText);
        }
    }
    var theData="";
    ajaxObject.setRequestHeader("Content-length", theData.length);
    ajaxObject.setRequestHeader("Connection", "close");
    ajaxObject.setRequestHeader("recipeId", recipeId);
    ajaxObject.setRequestHeader("recipeRate", rating);


    document.getElementById('saving-msg').style.visibility="visible";
    document.getElementById('saving-msg').style.display="block";
    document.getElementById('show-rating-stars').style.visibility="hidden";
    document.getElementById('show-rating-stars').style.display="none";

    var cookieValue = getCookie('emend-recipe');
    if (cookieValue == null)
    {
        setCookie('emend-recipe',recipeId+'::');
    }
    else
    {
        setCookie('emend-recipe',cookieValue+recipeId+'::');
    }

    ajaxObject.send(theData);
}

/*
 * Callback function to display results.
 */
function displayResults(response) {
    try {
        var elements = response.replace(/^\s*/, "").replace(/\s*$/, "").split("||");
        var ele = document.getElementsByName('number-of-ratings');
        var ratingText = "Ratings";
        if (elements[1] == 1)
        {
            var ratingText = "Rating";
        }

        for(var i=0;i < ele.length;i++)
        {
            ele[i].innerHTML=elements[1]+"&nbsp;"+ratingText;
        }
		document.getElementById('number-of-ratings1').innerHTML=elements[1]+"&nbsp;"+ratingText;
        var r = elements[0].replace(".","-");
        var ele2 = document.getElementById('rating-stars');
        ele2.className="ratings ratings-"+r;

        document.getElementById('show-rating-stars').style.visibility="visible";
        document.getElementById('show-rating-stars').style.display="block";
        document.getElementById('saving-msg').style.visibility="hidden";
        document.getElementById('saving-msg').style.display="none";

        setStarsToStatic();
    }
    catch (exception){}
}




function setEmailAFriendSubject(theSubject)
{
    var subject = document.getElementById('subject');
    subject.value = theSubject;
    return true;
}

function emailRecipeToFriend(theForm)
{
    var ajaxObject = null;
    if(window.XMLHttpRequest)
    {
        ajaxObject = new XMLHttpRequest();
    }
    else if(new ActiveXObject('Msxml2.XMLHTTP'))
    {
        ajaxObject = new ActiveXObject('Msxml2.XMLHTTP');
    }
    else if(new ActiveXObject('Microsoft.XMLHTTP'))
    {
        ajaxObject = new ActiveXObject('Microsoft.XMLHTTP');
    }

    var theData="";
    theData  = "formname="+ theForm.formname.value;
    theData += "&reqf="   + theForm.reqf.value;
    theData += "&emailAFriend=true";
    theData += "&subject=" + document.getElementById('subject').value;
    theData += "&question(referer)="+document.getElementById('recipeId').value;
    theData += "&toEmail=" + theForm.toEmail.value;
    theData += "&firstname=" + theForm.firstname.value;
    theData += "&yourName=" + theForm.yourname.value;
    theData += "&fromEmail=" + theForm.fromEmail.value;
    var emailFile = theForm.emailFile;
    if (emailFile[0].checked)
    {
        theData += "&emailFile="+emailFile[0].value;
    }
    else
    {
        theData += "&emailFile="+emailFile[1].value;
    }


    var theAction = theForm.getAttribute("action");

    ajaxObject.open("POST", theAction, true);
    ajaxObject.onreadystatechange = function()
    {
        if(ajaxObject.readyState==4)
        {
            getEmailResult(ajaxObject.responseText);
        }
    }
    ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajaxObject.setRequestHeader("Content-length", theData.length);
    ajaxObject.setRequestHeader("Connection", "close");
    ajaxObject.send(theData);
    return false;
}

/*
 * Callback function to display results.
 */
function getEmailResult(response)
{
    try
    {
        var answer=response.replace(/^\s*/, "").replace(/\s*$/, "");
        if (answer=="0")
        {
            Recipes.EmailSignup.showThankYouScreen();
        }
        else
        {
            Recipes.EmailSignup.showErrorScreen();
        }
    }
    catch (exception)
    {
        alert(exception);
    }
}

function setStatic(ele,i)
{
    ele.onclick = '';
    ele.className = '';
    ele.style.cursor='default';
    var children = ele.childNodes;
    // Remove anchor tag so the stars do not move
    for (var i=0; i < children.length; i++)
    {
        var child = children[i];
        if (child.tagName != undefined)  // Need for IE6
        {
            if (child.tagName.toUpperCase() == 'A')
            {
                ele.removeChild(child);
                i--;
            }
        }
    }
}

// IE6 does not support getElementsByName(), so changed to use tag ids rather than tag names
function setStarsToStatic()
{
    var ele = document.getElementById('dynamic_stars_1');
    setStatic(ele,1);

    ele = document.getElementById('dynamic_stars_2');
    setStatic(ele,2);

    ele = document.getElementById('dynamic_stars_3');
    setStatic(ele,3);

    ele = document.getElementById('dynamic_stars_4');
    setStatic(ele,4);

    ele = document.getElementById('dynamic_stars_5');
    setStatic(ele,5);
}
