function RateAndReviewRecipe(recipeId, txtReviewId, recipeName, recipeImage, socNetDomain, message, event) {
    $('span.error').hide();

    var eventArg = event || window.event;

    if (eventArg)
        var target = eventArg.target || eventArg.srcElement;

	var review = EncodeText($('#' + txtReviewId).val());
    review = escape(review);
    var rating = getRateValue();
    if (rating <= 0) {
        $('span.error').show();
        return;
    }

    recipeName = EncodeText(recipeName);
    recipeName = escape(recipeName);

    var xmlInput = "<input><recipeId>" + recipeId + "</recipeId><ratingValue>" + rating + "</ratingValue><review>" + review + "</review><recipeName>" + recipeName + "</recipeName><recipeImageURL>" + recipeImage + "</recipeImageURL></input>";
    var remoteInput = "<remoteInput>xmlInput=" + xmlInput + "</remoteInput>";

    var xmlData = "<remoteUrl>" + socNetDomain + "/Services/ContentServicePage.aspx" + "</remoteUrl><postData><remoteMethod>method=RateAndReviewRecipe</remoteMethod>" + remoteInput + "</postData>";

    xmlInput = PrepareXmlInput(xmlData);

    $.ajax({
        type: "POST",
        url: "/httpservices/proxyservice.aspx",
        data: "method=RemotePost&xmlInput=" + xmlInput,
        error: function(XMLHttpRequest, recipeId, errorThrown) {
            if (target) target.disabled = false;
        },
        success: function(xml) {

            var threadId, date;

            $(xml).find('output').each(function(i) {
                threadId = $(this).find("threadId").text();
                date = $(this).find("date").text();
            });
            if (date) {
                $('#' + txtReviewId).val('');
                GetRateObject().$cancel.click();

                $("#divRateDate").text(message.replace("[DATE]", date));
                $("#divRateDate").show();

                ResetCounter(txtReviewId);
                RepeaterDataBind(recipeId);
            }
        },
        beforeSend: function(xml) {
            if (target) target.disabled = true;
        },
        complete: function(request, settings) {
            if (target) target.disabled = false;
        }
    });
}

function ResetCounter(textBoxId) {
    var counterLabelId = $('#' + textBoxId).attr("labelid");
    var charsCount = $('#' + textBoxId).attr("showcounter");

    $('#' + counterLabelId).text(charsCount);
}

function GetRatingValues(serviceDomain) {
    var xmlRemoteInput = "<input><contentTypeId>1</contentTypeId></input>";
    var xmlData = "<remoteUrl>" + serviceDomain + "/Services/ContentServicePage.aspx" + "</remoteUrl><postData><remoteMethod>method=GetContentRatings</remoteMethod><remoteInput>xmlInput=" + xmlRemoteInput + "</remoteInput></postData>";

    var xmlInput = PrepareXmlInput(xmlData);

    $.ajax({
        type: "POST",
        url: "/httpservices/proxyservice.aspx",
        data: "method=RemotePost&xmlInput=" + xmlInput,
        error: function(XMLHttpRequest, xmlInput, errorThrown) {
        },
        success: function(xml) {

            $(xml).find('output').find('ContentRating').each(function(i) {
                var optionTemplate = '<option value="[VALUE]">[ALTERNATETEXT]</option>';
                optionTemplate = optionTemplate.replace("[VALUE]", $(this).find("Value").text());
                optionTemplate = optionTemplate.replace("[ALTERNATETEXT]", $(this).find("AlternateText").text());
                $("#RateAfterButtonClick").append(optionTemplate);
            });
        }
    });
}

function GetLastRateDate(contentId, contentTypeId, serviceDomain) {
    var xmlInput = "<input><contentId>" + contentId + "</contentId><contentTypeId>" + contentTypeId + "</contentTypeId></input>";
    var remoteInput = "<remoteInput>xmlInput=" + xmlInput + "</remoteInput>";

    var xmlData = "<remoteUrl>" + serviceDomain + "/Services/ContentServicePage.aspx" + "</remoteUrl><postData><remoteMethod>method=GetLastRateDate</remoteMethod>" + remoteInput + "</postData>";

    xmlInput = PrepareXmlInput(xmlData);

    $.ajax({
        type: "POST",
        url: "/httpservices/proxyservice.aspx",
        data: "method=RemotePost&xmlInput=" + xmlInput,
        error: function(XMLHttpRequest, contentId, errorThrown) {
        },
        success: function(xml) {

            var message = $("#divRateDate").text();
            var date;
            $(xml).find('output').each(function(i) {
                date = $(this).find("date").text();
            });

            if (date && date != null && date != "") {
                message = message.replace("[DATE]", date);
                $("#divRateDate").text(message);
            }
            else { $("#divRateDate").hide() }
        }
    });
}

function GetRateObject() {
    return $("#AfterButtonClick").data("stars");
}

function getRateValue() {
    return GetRateObject().options.value;

}


function ActivateRecipeDetailsTab() {
    $($('#tabs_container > .tabs > li')[1]).removeClass('active');
    $($('#tabs_container > .tabs > li')[0]).addClass('active');
    $('div.tab_contents_active').removeClass('tab_contents_active');
    $($('div.tab_contents')[0]).addClass('tab_contents_active');
    $('#tab').val(1);
}

function ActivateRecipeReviewsTab() {
    $($('#tabs_container > .tabs > li')[0]).removeClass('active');
    $($('#tabs_container > .tabs > li')[1]).addClass('active');
    $('div.tab_contents').removeClass('tab_contents_active');
    $($('div.tab_contents')[1]).addClass('tab_contents_active');
    $('#tab').val(2);
    
    $('#' + GetDivSortingID()).attr("style","display:block");
}

function UpdateRecipeReviewsTabNumber(TotalCount) {
    if (TotalCount > 0) {
        var RecipeReviewsTabNumber = document.getElementById("lnkRecipeReviewsTab");
        RecipeReviewsTabNumber.innerHTML = GetReviewsTabText() + " (" + TotalCount + ")";
    }
}

function RepeaterDataBind(contentId) {
    var sortOpt = getParameterByName("sort");
    if (sortOpt == "")
    {
        sortOpt = 3;
    }
    SetPageIndex(1, GethdnPageIndexID());
    GetThreadsByRecipeId(contentId, parseInt(sortOpt), 1, 4);    
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

/* 
****************************************************
****************************************************
****************************************************
UpdateHelpfulVotes Functions 
****************************************************
****************************************************
****************************************************
*/
function UpdateHelpfulVotes(threadId, spanHelpfulVotesId, divHelpfulLinkId, divVotesCountId) {
    var xmlInput = GetUpdateHelpfulVotesXmlInput(threadId);
    $.ajax({
        type: "POST",
        url: "/httpservices/proxyservice.aspx",
        data: "method=RemotePost&xmlInput=" + xmlInput,
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + " " + errorThrown); },
        success: function(xml) {
            UpdateHelpfulNumber(spanHelpfulVotesId, divHelpfulLinkId, divVotesCountId);
        } //end of success handler
    });
}

function GetUpdateHelpfulVotesXmlInput(threadId) {
    var xmlInput = "<input><threadId>" + threadId + "</threadId></input>";
    var remoteInput = "<remoteInput>xmlInput=" + xmlInput + "</remoteInput>";
    var xmlData = "<remoteUrl>" + GetSocNetDomain() + "/Services/ContentServicePage.aspx" + "</remoteUrl><postData><remoteMethod>method=UpdateHelpfulVotes</remoteMethod>" + remoteInput + "</postData>";
    return PrepareXmlInput(xmlData);
}

function UpdateHelpfulNumber(spanHelpfulVotesId, divHelpfulLinkId, divVotesCountId) {
    var spanHelpfulVotes = document.getElementById(spanHelpfulVotesId);
    var divHelpfulLink = document.getElementById(divHelpfulLinkId);
    var intCount = 0;
    if (spanHelpfulVotes.innerHTML != "") {
        intCount = parseInt(spanHelpfulVotes.innerHTML);
    }
    spanHelpfulVotes.innerHTML = intCount + 1;
    $("#" + divVotesCountId).attr('style', 'display:block');
    divHelpfulLink.innerHTML = "<i>You found this review helpful.</i>";
}


/* 
****************************************************
****************************************************
****************************************************
GetThreadsByRecipeId Functions 
****************************************************
****************************************************
****************************************************
*/
function GetThreadsByRecipeId(contentId, sortOptions, offSet, pageSize) {
    var xmlInput = GetThreadsByRecipeIdXmlInput(contentId, sortOptions, offSet, pageSize);
    var ratings = new Array();
    var AuthorName = "";
    var TotalCount = "0";
    $.ajax({
        type: "POST",
        url: "/httpservices/proxyservice.aspx",
        data: "method=RemotePost&xmlInput=" + xmlInput,

        error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + " " + errorThrown); },
        success: function(xml) {
            $(xml).find('output').find('Threads').find('Thread').each(function(i) {
                var ID = $(this).find("ID").text();
                var AuthorSID = $(this).find("AuthorSID").text();
                var ReviewText = $(this).find("ReviewText").text();
                var RatingValue = $(this).find("RatingValue").text();
                var HelpfulVotes = $(this).find("HelpfulVotes").text();
                var IsVoted = $(this).find("IsVoted").text();
                var contentId = $(this).find("contentId").text();
                var PostsCount = $(this).find("PostsCount").text();
                var CreationDate = $(this).find("CreationDate").text();
                AuthorName = $(this).find("AuthorName").text();
                var IsPostedBeforePV2 = $(this).find("IsPostedBeforePV2").text();

                rating = new RatingObject(ID, AuthorSID, ReviewText, RatingValue, HelpfulVotes, IsVoted, contentId, PostsCount, CreationDate, AuthorName, IsPostedBeforePV2);
                ratings.push(rating);
            });

            $(xml).find('output').each(function(i) {
                TotalCount = $(this).find("TotalCount").text();
            });

            UpdateRecipeReviewsTabNumber(TotalCount);

            var pageCount = GetPageCount(TotalCount, pageSize);

            if (ratings.length > 0) {
                $("#reviewsTable").show();
                $("#divPaging").show();
                $('#' + GetDivSortingID()).attr("style", "display:block");
                $('#' + GetDivRecipeNotReviewedID()).attr("style", "display:none");
                
                if (ratings.length == 1) {
                    $('#' + GetHdnIsLastRecordID()).val("True");
                }
                else {
                    $('#' + GetHdnIsLastRecordID()).val("False");
                }

                //append paging
                var ratingTemplate = "";
                var pagingTemplate = "";

                $("#reviewsTable").empty();                
                for (var i = 1; i <= ratings.length; i++) {
                    ratingTemplate = ratingTemplate + GetRatingTemplate(ratings[(i - 1)]);
                    $("#reviewsTable").append(ratingTemplate);
                    ratingTemplate = "";
                }                
                //Get Page Number
                pageNumber = "" != $('#' + GethdnPageIndexID()).val() ? parseInt($('#' + GethdnPageIndexID()).val()) : 1;

                var iUpto;
                var iStart = ((parseInt(pageNumber) - 1) * parseInt(pageSize)) + 1;
                if (pageNumber == pageCount) {
                    iUpto = TotalCount;
                }
                else {
                    iUpto = parseInt(iStart) + parseInt(pageSize) - 1;
                }

                $("#divPaging").empty();
                $("#divPaging").append('<span style="FLOAT: right">');
                //Add First
                if (parseInt(pageNumber) != 1) {
                    $("#divPaging").append(GetPagingTemplate(contentId, sortOptions, GetOffset(1, pageSize), pageSize, AuthorName, 1, "First"));
                }
                //Add Previous
                if (parseInt(pageNumber) > 1) {
                    $("#divPaging").append(GetPagingTemplate(contentId, sortOptions, GetOffset((parseInt(pageNumber) - 1), pageSize), pageSize, AuthorName, (parseInt(pageNumber) - 1), "Previous"));
                }
                for (var i = 1; i <= pageCount; i++) {
                    if (i >= (pageNumber - (2)) && i <= (pageNumber + (2))) {
                        pagingTemplate = GetPagingTemplate(contentId, sortOptions, GetOffset(i, pageSize), pageSize, AuthorName, i, i);
                        $("#divPaging").append(pagingTemplate);
                        pagingTemplate = "";
                    }
                }
                //Add Next
                if (parseInt(pageNumber) < parseInt(pageCount)) {
                    $("#divPaging").append(GetPagingTemplate(contentId, sortOptions, GetOffset((parseInt(pageNumber) + 1), pageSize), pageSize, AuthorName, (parseInt(pageNumber) + 1), "Next"));
                }
                //Add Last
                if (pageNumber != pageCount) {
                    $("#divPaging").append(GetPagingTemplate(contentId, sortOptions, GetOffset(pageCount, pageSize), pageSize, AuthorName, pageCount, "Last"));
                }
                $("#divPaging").append('</span>');
                //End Paging

                if (pageCount <= 1) {
                    $("#divPaging").hide();
                }
                else {
                    $("#divPaging").show();
                }                
            }
            else {                
                if (TotalCount > 0) {
                    SetPageIndex(pageCount, GethdnPageIndexID());
                    GetThreadsByRecipeId(contentId, sortOptions, GetOffset(pageCount, pageSize), pageSize);
                }
                else {
                    $("#reviewsTable").hide();
                    $("#divPaging").hide();
                    $('#' + GetDivSortingID()).attr("style", "display:none");
                    $('#' + GetDivRecipeNotReviewedID()).attr("style", "display:block");
                }
            }
            //Return To Top
            window.scrollTo(0, 0);
        } //end of success handler
    });
}

function GetThreadsByRecipeIdXmlInput(contentId, sortOption, offSet, count) {
    var xmlInput = "<input><contentId>" + contentId + "</contentId><sortOption>" + sortOption + "</sortOption><offset>" + offSet + "</offset><count>" + count + "</count><contentTypeId>1</contentTypeId></input>";
    var remoteInput = "<remoteInput>xmlInput=" + xmlInput + "</remoteInput>";
    var xmlData = "<remoteUrl>" + GetSocNetDomain() + "/Services/ContentServicePage.aspx" + "</remoteUrl><postData><remoteMethod>method=GetContentReviews</remoteMethod>" + remoteInput + "</postData>";
    return PrepareXmlInput(xmlData);
}

function RatingObject(ID, AuthorSID, ReviewText, RatingValue, HelpfulVotes, IsVoted, contentId, PostsCount, CreationDate, AuthorName, IsPostedBeforePV2) {
    this.ID = ID;
    this.AuthorSID = AuthorSID;
    this.ReviewText = ReviewText;
    this.RatingValue = RatingValue;
    this.HelpfulVotes = HelpfulVotes;
    this.IsVoted = IsVoted;    
    this.contentId = contentId;    
    this.PostsCount = PostsCount;
    this.CreationDate = CreationDate;
    this.AuthorName = AuthorName;
    this.IsPostedBeforePV2 = IsPostedBeforePV2;
}

function GetRatingTemplate(rating) {
    var isVoted = rating.IsVoted;
    var helpfulDiv = "";
    var ReportLink = "";
    var divVotesDisplay = "display:none;";
    var divPv2NoteTemplate = GetTemplatePV2Note();

    if (HelpfulVoteIsAllowed() == "True" && rating.AuthorSID != GetCurrentUserSid()) {
        if (isVoted != "True") {
            var helpfulDiv = GetNotVotedTemplate();
        }
        else {
            var helpfulDiv = GetVotedTemplate();
        }
    }

    if (rating.AuthorSID == GetCurrentUserSid() && NotIsVisitor() == "True") {
        ReportLink = GetRemoveLinkTemplate();
    }    
    
    if (NotIsVisitor() == "True" && (rating.AuthorSID != GetCurrentUserSid())) {
        ReportLink = GetReportLinkTemplate();
    }
    if (rating.HelpfulVotes > 0) {
        divVotesDisplay = "display:block;";
    }
    //PV2 Note
    if (rating.IsPostedBeforePV2 == "True") {
        divPv2NoteTemplate = ReplaceKey(divPv2NoteTemplate, "[pv2notedisplay]", "display:block;");
    }
    else {
        divPv2NoteTemplate = ReplaceKey(divPv2NoteTemplate, "[pv2notedisplay]", "display:none;");
    }

    var itemTemplate = GetTemplate();
    //First replace links templates
    itemTemplate = ReplaceKey(itemTemplate, "[helpfulDiv]", helpfulDiv);
    itemTemplate = ReplaceKey(itemTemplate, "[ReportLink]", ReportLink);
    itemTemplate = ReplaceKey(itemTemplate, "[divVotesDisplay]", divVotesDisplay);
    //replace the values
    itemTemplate = ReplaceKey(itemTemplate, "[PV2NoteText]", divPv2NoteTemplate);
    itemTemplate = ReplaceKey(itemTemplate, "[contentId]", rating.contentId);    
    itemTemplate = ReplaceKey(itemTemplate, "[AuthorSID]", rating.AuthorSID);
    itemTemplate = ReplaceKey(itemTemplate, "[AuthorName]", rating.AuthorName);
    itemTemplate = ReplaceKey(itemTemplate, "[RatingValue]", rating.RatingValue);
    itemTemplate = ReplaceKey(itemTemplate, "[ReviewText]", rating.ReviewText);
    itemTemplate = ReplaceKey(itemTemplate, "[ID]", rating.ID);
    itemTemplate = ReplaceKey(itemTemplate, "[HelpfulVotes]", rating.HelpfulVotes);    
    itemTemplate = ReplaceKey(itemTemplate, "[PostsCount]", rating.PostsCount);
    itemTemplate = ReplaceKey(itemTemplate, "[CreationDate]", rating.CreationDate);
    
    return itemTemplate;
}

function ReplaceKey(text, pattern, newKey) {
    pa = new RegExp("\\" + pattern, "g");
    return text.replace(pa, newKey);
}

function GetPagingTemplate(contentId, sortOptions, offSet, pageSize, AuthorName, index, text) {
    var currentPage = $('#' + GethdnPageIndexID()).val();
    if (currentPage == index) {
        var itemTemplate = '<a disabled="disabled">' + text + '</a>&nbsp;';
    }
    else {
        var itemTemplate = '<a onclick="SetPageIndex(\'' + index + '\', \'' + GethdnPageIndexID() + '\')" href="javascript:GetThreadsByRecipeId(\'' + contentId + '\', \'' + sortOptions + '\', \'' + offSet + '\', \'' + pageSize + '\')">' + text + '</a>&nbsp;';
    }
    return itemTemplate;
}

function SetPageIndex(pageNumber, hdnPageIndexID) {
    $('#' + hdnPageIndexID).val(pageNumber);
}

function GetOffset(pageNumber, pageSize) {
    return ((parseInt(pageNumber) * parseInt(pageSize)) - parseInt(pageSize)) + 1;
}

function GetPageCount(totalCount, PAGE_SIZE) {
    var dblPageCount = Math.ceil(parseInt(totalCount) / parseInt(PAGE_SIZE));
    return parseInt(dblPageCount);
}
