﻿var tabArray = new Array("General", "Hazard", "Comfort", "Grip", "Results");
var tabPrefix = "Tab";
var containerPrefix = "Container";
var currentSelectedIndex = -1;
function showTabIndex(newIndex)
{
    if(currentSelectedIndex!=-1)
    {
        $(tabArray[currentSelectedIndex] + tabPrefix).removeClassName("Selected");
        $(tabArray[currentSelectedIndex] + containerPrefix).hide();
    }
    currentSelectedIndex = newIndex;
    $(tabArray[currentSelectedIndex] + tabPrefix).addClassName("Selected");
    $(tabArray[currentSelectedIndex] + containerPrefix).show();
    
    $("HeaderImage").src = "/images/" + tabArray[currentSelectedIndex] + "Hdr.gif";
    
    
    SetButtons();
    
    //$("TitleHeader").innerHTML = "<h1>" + tabArray[currentSelectedIndex] + "</h1>";

    return true;
}

function nextTab()
{
    if (currentSelectedIndex == tabArray.length - 1) return;

    if(currentSelectedIndex!=-1)
    {
        $(tabArray[currentSelectedIndex] + tabPrefix).removeClassName("Selected");
        $(tabArray[currentSelectedIndex] + containerPrefix).hide();
    }
    currentSelectedIndex = currentSelectedIndex+1;
    $(tabArray[currentSelectedIndex] + tabPrefix).addClassName("Selected");
    $(tabArray[currentSelectedIndex] + containerPrefix).show();
    
    $("HeaderImage").src = "/images/" + tabArray[currentSelectedIndex] + "Hdr.gif";
    
    SetButtons();
    
    
    if (currentSelectedIndex == tabArray.length - 1) search();
    
}

function previousTab()
{
    if(currentSelectedIndex == 0) return;

    if(currentSelectedIndex!=-1)
    {
        $(tabArray[currentSelectedIndex] + tabPrefix).removeClassName("Selected");
        $(tabArray[currentSelectedIndex] + containerPrefix).hide();
    }
    currentSelectedIndex = currentSelectedIndex-1;
    $(tabArray[currentSelectedIndex] + tabPrefix).addClassName("Selected");
    $(tabArray[currentSelectedIndex] + containerPrefix).show();
    
    $("HeaderImage").src = "/images/" + tabArray[currentSelectedIndex] + "Hdr.gif";
    
    SetButtons();
}

function SetButtons()
{
    if(currentSelectedIndex == 0)
    {
        $("PreviousBtn").src = "/images/PreviousBtnOff.gif";
        $("NextBtn").src = "/images/NextBtnOn.gif";
    }
    else if(currentSelectedIndex == tabArray.length - 1)
    {
        $("PreviousBtn").src = "/images/PreviousBtnOn.gif";
        $("NextBtn").src = "/images/NextBtnOff.gif";
    }
    else
    {
        $("PreviousBtn").src = "/images/PreviousBtnOn.gif";
        $("NextBtn").src = "/images/NextBtnOn.gif";    
    }     
}



var results;
var maxInSideBar = 3;




function search()
{
    new Ajax.Request
    ("/AnsellService.asmx/Search", { contentType:"application/json",method: "post",postBody:Object.toJSON(postBody),
        onSuccess:function (res)
        {
            results = res.responseText.evalJSON(true).d;

            var gloves = results.Gloves;
            //Update side results bar
            var resultSummary = "<h1>Quick Results</h1><small>Found " + results.RecordCount + " gloves.<br/>Top " + maxInSideBar + " Glove(s):</small>";
            var templateSummary = new Template("<div style=\"margin-top:10px;\"><div style=\"font-weight: bold;\">#{Name} - #{Score} %</div>#{Code}</div>");
            for(var i=0; i < gloves.length && i <maxInSideBar; i++)
            {
                resultSummary += templateSummary.evaluate(gloves[i]);
            }
            resultSummary+= "<strong style=\"margin-top: 20px; color: #cc0000; display:block;\">Results are based on incomplete Response.</strong>";
            
            // TempResults currently disabled.
            //$("TempResultsContainer").update(resultSummary);
            
            
            
            
            
            
            //Update Results
            var resultDetail = "";
            //var templateDetail = new Template("<div class=\"row\">#{Name}: #{Score}% matched #{Code}</div>");
            
            var templateDetail = new Template("\
<tr>\
    <td class='Number'>#{Number}.</td>\
    <td class='Item'>\        <div class='GloveImage'>#{ImageTag}</div>\        <div class='Description'>\            <a href='#' onclick='ShowGlove(#{ProductId})'>\                <h3>#{Name}</h3>\            </a>\
            <div class='Blurb'>#{Description}</div>\
        </div>\
        <div class='Rank'><h3>#{Score}%</h3></div>\
    </td>\
</tr>");
            
            var imageTagTemplate = new Template("<img src='#{ImageUrl}' height='79' width='79' />");
            
            for(var i=0; i < gloves.length && i < 3; i++)
            {
                gloves[i].Number = i + 1;
                
                if(gloves[i].ImageUrl!=null && gloves[i].ImageUrl != "")
                    gloves[i].ImageTag = imageTagTemplate.evaluate(gloves[i]);
                
                resultDetail += templateDetail.evaluate(gloves[i]);
            }
            
            $("ResultList").update(resultDetail);
            
            if(gloves.length==0)
            {
                $("ResultList").update("<tr><td style=\"font-weight:bold;padding: 10px;\">No results found, click <a href=\"#\" onclick=\"return showTabIndex(0);\">here</a> to modify your search criteria.</td></tr>");
                $("ctl00_BodyPlaceHolder_SearchResultsControl_ResultsDescription").hide();
                $("SaveAndEmail").hide();
            }
            else
            {
                $("ctl00_BodyPlaceHolder_SearchResultsControl_ResultsDescription").show();
                $("SaveAndEmail").show();
            }
            
            
            
            
            //Update Results
            resultDetail = "";            
            templateDetail = new Template("\
<tr>\
    <td class='Number'>#{Number}.</td>\
    <td class='Item'>\        <div class='Description'>\            <a href='#' onclick='ShowGlove(#{ProductId})'>\                <h3>#{Name}</h3>\            </a>\
        </div>\
        <div class='Rank'><h3>#{Score}%</h3></div>\
    </td>\
</tr>");
            if(gloves.length>3)
                for(var i=3; i < gloves.length; i++)
                {
                    gloves[i].Number = i + 1;
                    resultDetail += templateDetail.evaluate(gloves[i]);
                }
            $("AdditionalResultList").update(resultDetail);
            if(gloves.length<=3)
                $("AdditionalResultsHolder").hide();
            else
                $("AdditionalResultsHolder").show();
        }
    }
    );
    return true;
}


/**
 * Returns the value of the selected radio button in the radio group
 * 
 * @param {radio Object} or {radio id} el
 * OR
 * @param {form Object} or {form id} el
 * @param {radio group name} radioGroup
 */
function $RF(el, radioGroup) {
	if($(el).type == 'radio') {
		var el = $(el).form;
		var radioGroup = $(el).name;
	} else if ($(el).tagName.toLowerCase() != 'form') {
		return false;
	}
	return $F($(el).getInputs('radio', radioGroup).find(
		function(re) {return re.checked;}
	));
}






// [MR]
function SaveSearch(container)
{ 
    var isValid = true;
    var message = "";
    
    var description = container.DescriptionControl.value;
    
    if(description == "")
    {
        message += "<li>Description is required.</li>";
        isValid = false;
    }
    
    if(!isValid)
    {
        message = "<ul>" + message + "</ul>";
        container.FeedbackControl.update(message);
        return;
    }



    var _postBody = new Object();
    _postBody.searchId = container.SearchId;
    _postBody.description = description;
    _postBody.searchRequest = postBody.request;

    new Ajax.Request("/AnsellService.asmx/SaveSearch", 
        { contentType: "application/json", method: "post", postBody: Object.toJSON(_postBody),
            onSuccess: function(response)
            {
                var searchId = response.responseText.evalJSON(true).d;
                
                if(searchId <= 0)
                {
                    message = "Sorry, there was a problem saving your search.";
                }
                else
                {
                    container.SearchId = searchId;
                    message = "Saved successfully!";
                }
                
                container.FeedbackControl.update(message);
            }
        }
    );
}



// [MR]
function EmailFriend(container)
{
    var isValid = true;
    var message = "";
    
    var name = container.NameControl.value;
    var emailAddress = container.EmailAddressControl.value;
    
    if(name == "")
    {
        message += "<li>Name is required.</li>";
        isValid = false;
    }
    
    if(emailAddress == "")
    {
        message += "<li>Email Address is required.</li>";
        isValid = false;
    }
    
    if(!isValid)
    {
        message = "<ul>" + message + "</ul>";
        container.FeedbackControl.update(message);
        return;
    }
    
    

    var _postBody = new Object();
    _postBody.name = name;
    _postBody.address = emailAddress;
    _postBody.personalMessage = container.PersonalMessageControl.value;

    var requestUrl;

    if (container.CommandName == "Search")
    {
        _postBody.searchRequest = postBody.request;
        requestUrl = "/AnsellService.asmx/SendSearch";
    }
    else if (container.CommandName == "Product")
    {
        _postBody.productId = container.ProductId;
        requestUrl = "/AnsellService.asmx/SendProduct";
    }

    new Ajax.Request (requestUrl, 
        { contentType: "application/json", method: "post", postBody: Object.toJSON(_postBody),
            onSuccess: function(response)
            {
                var sent = response.responseText.evalJSON(true).d;  

                if (sent)
                {
                    message = "Message sent successfully!";
                    container.NameControl.value = "";
                    container.EmailAddressControl.value = "";
                    container.PersonalMessageControl.value = "";
                }
                else
                {
                    message = "Sorry, there was a problem sending your message.";
                }
                     
                container.FeedbackControl.update(message);
            }
        }
    );
}


// [MR]
function ShowGloveDetails(container, productId)
{  
    var _postBody = { searchRequest: null, productId: productId };
    
    if(postBody != null)
        _postBody.searchRequest = postBody.request;

    new Ajax.Request("/AnsellService.asmx/GetGlove", 
        { contentType: "application/json", method: "post", postBody: Object.toJSON(_postBody),
            onSuccess: function(response)
            {
                var glove = response.responseText.evalJSON(true).d;
                var imageTag = "";

                if (glove.ImageUrl == "")
                {
                    container.ImageControl.hide();
                }
                else
                {
                    imageTag = "<img style=\"float:left;margin: 5px;\" src=\"" + glove.ImageUrl + "\" alt=\"" + glove.Name + "\"/>";
                }    
                
                container.NameControl.update(glove.Name);
                container.DescriptionControl.update(imageTag + glove.Description);
                container.ChartContainerControl.update(glove.RadarChart);
                
                if(postBody != null)
                {
                    var score = "(" + glove.Score + "% match)";
                    container.ScoreControl.update(score);
                }
            } 
        }
    );
}


