﻿window.addEvent('domready', function(){
    initHTF();
});

// TODO Fix lang. Add hidden field with default value.
var searchInputDefaultText;
var searchString = null;
var chatName = "";
var chatCompany = "";
var chatSessionId;
var chatTimer;
function initHTF()
{
    // set default input text
    searchInputDefaultText = Locale.SearchBoxInputWatermark; 
    // check for search box and add events
    if ($('txtSearch') != null)
    {
        searchInput = $('txtSearch');
        if (searchString != null && searchString != "")
        {
            searchInput.value = searchString;
        }
        else if (searchInput.value.length == 0)
        {
            searchInput.value = searchInputDefaultText;
        }
        
        searchInput.addEvent('focus', function(){
            if ($('txtSearch').value == searchInputDefaultText)
            {
                $('txtSearch').value = "";
            }
        });
        
        searchInput.addEvent('blur', function(){
            if ($('txtSearch').value == "")
            {
                $('txtSearch').value = searchInputDefaultText;
            }
        });
        
        searchButton = $(btnSearchId);
        
        searchButton.addEvent('click', function(event){
                // TODO: validate input
                queueSearch($('txtSearch').value);
        });        
        searchInput.addEvent('keypress', function(event){
            if (event.code == 13)
            {
                queueSearch($('txtSearch').value);
                return false;
            }
        });        
        
        if (typeof(btnQuoteId) != "undefined")
        {
            quoteButton = $(btnQuoteId);
            quoteButton.addEvent('click', function(event){
                searchQuery = "";
                parts = "";
                checkboxes = $$("input.quote");
                id = "1";
                for(i= 0;i <checkboxes.length; i++)
                {
                    if (checkboxes[i].checked)
                    {
                        if (parts != "")
                            parts += "|";
                        parts += checkboxes[i].value;
                    }
                }
                
                url = quoteUrl + "?q=" + searchString + "&parts=" + parts;
                document.location = url;
            });
        }
    }
    
}
/* chat */
    var chatSessionActive = false;
    function chatAppend(message, user)
    {
        if (user == null)
        {
            $('chatWindow').innerHTML += "<p class='user'>" + message + "</p>"; 
        }
        else if (user == "system")
        {
            $('chatWindow').innerHTML += "<p class='system'>" + message + "</p>"; 
        }
        else
        {
            $('chatWindow').innerHTML += "<p class='sales'>" + personalServiceOnlineUser.name + ": " + message + "</p>";
        }
        $('chatWindow').scrollTop = $('chatWindow').scrollHeight;
    }
    function enterChat_onMethodCompleted(result)
    {

        $('closewin').innerHTML = "Stäng: <a href='#' onclick='endChat();'>X</a>";
        chatSessionId = result;
        setTimeout("getChatMessages()", 2000);
        setTimeout("enterChat_Delayed()", 1500);
    }
    function enterChat_Delayed()
    {
        $('chat').style.display = 'block';
        $('chatConnecting').style.display = 'none';    
        chatAppend(Locale.ChatWelcome, 'system');
        chatSessionActive = true;
    }
    function enterChat_onMethodFailed(e)
    {
        if (e.get_exceptionType() == "HardToFind.WS.ChatNotAvailableException")
        {
            alert(Locale.ChatUnavailable);
            $('chatRegister').style.display = 'block';
            $('chatConnecting').style.display = 'none';             
        }
        else
        {
            showSessionEndedUnexpectedly();
        }
    }
    function sendChatMessage(message)
    {
        chatAppend(message);
        new HardToFind.WS.SearchAutoComplete.SendChatMessage(chatSessionId, message, function() {}, sendChatMessage_onMethodFailed);
    }
    
    function getChatMessages()
    {
        if (chatSessionActive)
        {
            new HardToFind.WS.SearchAutoComplete.GetChatMessages(chatSessionId, getChatMessages_onMethodCompleted, getChatMessages_onMethodFailed);       
        }
    }
    
    function getChatMessages_onMethodCompleted(messages)
    {
        setTimeout("getChatMessages()", 2000);
        for (i=0; i<messages.length; i++)
        {
            chatAppend(messages[i], personalServiceOnlineUser.name);
        }
    }
    
    function getChatMessages_onMethodFailed(e)
    {
        showSessionEndedUnexpectedly()
    }
    function sendChatMessage_onMethodFailed()
    {
        showSessionEndedUnexpectedly()
    } 
    function sendChatMessage_MethodCompleate()
    {

    }
    
    function endChat()
    {
        if (chatSessionActive)
        {
            new HardToFind.WS.SearchAutoComplete.EndChat(chatSessionId, endChat_onMethodCompleted); 
            chatSessionActive = false;
        }
    }
    
    function endChat_onMethodCompleted()
    {
        closepopup();
    }
    
    function showSessionEndedUnexpectedly()
    {
        $('closewin').innerHTML = "Stäng: <a href='#' onclick='closepopup();'>X</a>";
        $('chatbody').innerHTML = Locale.ChatUnexpectedErrorText;
    }
    
    function hasAvailableSession_onMethodComplete(result)
    {
        if (result == false)
        {
            alert(Locale.ChatUnavailable);
        }
        
    }
    
/* end chat */

function addEventRowHover(tblId)
{
    tbl = $(tblResultId);
    for (i = 0; i < tbl.rows.length; i++)
    {
        tbl.rows[i].c
        /*tbl.rows[i].addEvent("mouseenter", function(event) { 
            var tr;
            if (event.target.tagName.toLowerCase() == "tr")
                tr = event.target;            
            else if (event.target.parentNode.tagName.toLowerCase() == "tr")
                tr = event.target.parentNode;
            else if (event.target.parentNode.parentNode.tagName.toLowerCase() == "tr")
                tr = event.target.parentNode.parentNode;   
                            
            if (tr.className == "alt")
                tr.className = "altOver"; 
            else
                tr.className = "over"; 
        });
        
        tbl.rows[i].addEvent("mouseleave", function(event) { 
            var tr;
            if (event.target.tagName.toLowerCase() == "tr")
                tr = event.target;            
            else if (event.target.parentNode.tagName.toLowerCase() == "tr")
                tr = event.target.parentNode;
            else if (event.target.parentNode.parentNode.tagName.toLowerCase() == "tr")
                tr = event.target.parentNode.parentNode;   
                             
            if (tr.className == "altOver")
                tr.className = "alt"; 
            else
                tr.className = "";
        });*/
    }
}

function rowHover(elem)
{
    console.log("Hover");
    console.log(elem);
}

function rowOut(elem)
{
    console.log("Hover");
    console.log(elem);
}
function autoComplete_Populated(args)
{
}

/* Search */
    var tblResultId = "result";
    
    var storedQuery = "";
    function queueSearch(query)
    {
        // TODO: validate input
        if (query.length > 2)
        {
            storedQuery = query;
            HardToFind.WS.SearchAutoComplete.Search(   
             query, search_OnMethodCompleted);  
        }
        else    
            alert(Locale.QueueSearchInvalidLength);
    }

    function getResult(searchId, tbl)    
    {   
        tblResultId = tbl;
        $("loading").style.display = "block";
        try
        {
            HardToFind.WS.SearchAutoComplete.GetResult(   
                 searchId, getResult_onMethodCompleted, getResult_onMethodFailed, null );   
        }
        catch (Error)
        {
            alert("Got exception:"  +Error);
        }
    }                  
       
    function getResult_onMethodFailed()
    {
        // TODO: log error
        $("loading").style.display = "none";
        displayNothingFound()
    }
    
    function search_OnMethodCompleted(results)    
    {     
        searchId = results;
        document.location = searchUrl + "?q=" + storedQuery + "&id=" + searchId;
    }
    
    function getResult_onMethodCompleted(results)    
    {   
        $("loading").style.display = "none";
        if (results.length > 0)
        {
            $(btnQuoteId).style.display = "inline";
            if ($(tblResultId) == null)
            {
                addTable($("resultSet"), tblResultId);
            }        
            for(i = 0; i < results.length; i++)
            {
                addRow(tblResultId, results[i]);
            }
        }
        
        if (results.length == 0 && searchResultHits == 0)
        {
            displayNothingFound();
        }
        else
        {
            // bind event to all rows
            addEventRowHover();
        }
    }
    
    function displayNothingFound()
    {
        if (searchResultHits == 0)
        {
            $(pnlNothingFoundId).style.display = "block";    
        }
    }
    
    function addTable(parent, tblId)
    {
		
		var table = document.createElement("table");
		table.className = "result"
		table.cellSpacing = "0";
		table.cellPadding = "0";
		table.setAttribute("border", "0");
		table.setAttribute("id", tblId);
		//table.setAttribute("style", "border-collapse:collapse;");
		var row = table.insertRow(0);
		row.className = "head";
		var thQuote = document.createElement("th");
		thQuote.className = "left";
		thQuote.setAttribute("scope", "col");
		thQuote.innerHTML = Locale.ResultTableChoose;
		row.appendChild(thQuote);
		
		var thPartNo = document.createElement("th");
		thPartNo.setAttribute("scope", "col");
		thPartNo.innerHTML = Locale.ResultTablePartNo;
		row.appendChild(thPartNo);
		
		var thPartNo = document.createElement("th");
		thPartNo.setAttribute("scope", "col");
		thPartNo.innerHTML = Locale.ResultTableMfg;
		row.appendChild(thPartNo);
		
		var thDateCode = document.createElement("th");
		thDateCode.setAttribute("scope", "col");
		thDateCode.innerHTML = Locale.ResultTableDateCode;
		row.appendChild(thDateCode);				
		
		var thPack = document.createElement("th");
		thPack.setAttribute("scope", "col");
		thPack.innerHTML = Locale.ResultTableQuantity;
		row.appendChild(thPack);
		
		var thInfo = document.createElement("th");
		thInfo.className = "right";
		thInfo.setAttribute("scope", "col");
		thInfo.innerHTML = Locale.ResultTableInfo;
		row.appendChild(thInfo);		
		parent.appendChild(table);		
    }
    
    function addRow(tblId, data)
    {
        var tbl = $get(tblId);
        var row = tbl.insertRow(tbl.rows.length);
        if (tbl.rows.length % 2 == 1)
            row.className = "alt";
        var tdQuote = row.insertCell(0);
        tdQuote.className = "center";
        var tdPartNo = row.insertCell(1);
        var tdMfg = row.insertCell(2);
        var tdDateCode = row.insertCell(3);
        var tdQuantity = row.insertCell(4);
        var tdInfo = row.insertCell(5);
        var aPartNo = document.createElement("a");
        tdDateCode.innerHTML = data.DateCodeShort;
        var partId = "b" + data.StockItemId;
        aPartNo.setAttribute("href", quoteUrl + "?q=" + searchString + "&parts=" + partId + "," + partNoStr);
        var partNoStr = data.PartNo.toLowerCase().replace(searchString.toLowerCase(), "<b>" + searchString.toLowerCase() + "</b>");
        aPartNo.innerHTML = partNoStr;
        tdPartNo.appendChild(aPartNo);
        tdMfg.innerHTML = data.Mfg;
        tdQuantity.innerHTML = data.Quantity;
        tdInfo.innerHTML = "Available";
        
        var chkbox = document.createElement("input");
        chkbox.setAttribute("type", "checkbox");
        chkbox.setAttribute("value", partId + "," + data.PartNo);
        chkbox.className = "quote";
        
        tdQuote.appendChild(chkbox);
    }
    
    var popuproot;
    var popupwindow;
    var cnt = 0;
    function closepopup()
    {
        if (typeof(popuproot) != "undefined")
        {
            popuproot.style.display = 'none';
            popupwindow.style.display = 'none';
        }    
    }
    function showpopup(popuptype)
    {
        cnt++;
        if (typeof(popuproot) != "undefined")
            popuproot.style.display = 'block';
        else
            popuproot = document.createElement("div");
            
        if (typeof(popupwindow) != "undefined")
            popupwindow.style.display = 'block';
        else        
            popupwindow = document.createElement("div");
            
        popuproot.className = "popuproot";
        
		popupwindow.style.top = ((window.getHeight() - 400)/2).toInt() + "px";
		popupwindow.style.left = ((window.getWidth() - 520)/2).toInt() + "px";
        popupwindow.className = "popupwindow";
        popuproot.style.height = window.getScrollHeight() + 'px';
        popuproot.style.width = window.getScrollWidth() + 'px';
        var html =
              "<div class='wrapper'>"
            + "<div id='closewin'>Stäng: <a href='#' onclick='closepopup();'>X</a></div>"        
        if(popuptype== 'chat')
        {
            new HardToFind.WS.SearchAutoComplete.HasAvailableSession(hasAvailableSession_onMethodComplete);
            html +=
                  "<div class='chatwin'>"
                + "<img src='/Images/personalservice/" + personalServiceOnlineUser.userId + "-large.png' class='onlineperson' />"
                + "<div class='head'>"
                + "<h1>" + Locale.ChatHeading + "</h1>"
                + "<div class='onlinestatus'>Online:</div>"
                + "<div class='openinghours'>" + personalServiceOnlineUser.name + ", Tel. " + personalServiceOnlineUser.phone+ "</span></div></div>"
                + "<div id='chatbody'><div id='chatRegister' style='margin-top:25px;'>"
                + "<h1>" + Locale.ChatStartHeading + "</h1>"
                + "<p>" + Locale.ChatStartText + "</p>"
                + "<div style='margin-left: 15px;margin-top: 45px;'>"
                + "     <div style='width: 320px; text-align: right;margin-bottom: 15px;'><span style='font-size: 16px; color: #999;margin-right:8px;margin-right: 15px;'>" + Locale.ChatName + "</span>"
                + "     <input type='text' id='chatName' style='height: 22px;width: 150px;margin-right:8px;'/></div>"
                + "     <div style='width: 320px; text-align: right;'><span style='font-size: 16px; color: #999;margin-right:8px;margin-right: 15px;'>" + Locale.ChatCompany + "</span>"
                + "     <input type='text' id='chatCompany' style='height: 22px;width: 150px;margin-right:8px;'/></div>"
                + "     <input class='button' type='button' id='chatEnter' value='" + Locale.ChatStartButton + "' onclick='submitEnterChat();' />"
                + "</div>"
                + " </div>"
                + " <div id='chatConnecting' style='display: none;text-align:center;margin-top: 45px;'>"
                + "    Connecting...<br /><img src='/Images/loading_b.gif' alt='Connecting' />"
                + " </div>"
                + " <div id='chat' style='display: none;'>"
                + "     <div id='chatWindow' style='background-color: #eee;color: black; line-height: 160%;font-size: 13px;height:178px; overflow: scroll; padding: 10px;'></div>"
                + "     <textarea id='chatInput'></textarea>"
                + "<input class='button' type='button' id='chatEnd' value='" + Locale.ChatEndButton +"' onclick='endChat();' style='margin-top:8px; '/><br/>"
                + "<input class='button' type='button' id='chatSend' value='" + Locale.ChatSendButton + "' onclick='submitSendChatMessage();' style='margin-top:8px; '/>"
                + " </div>"
                + "</div></div>";
            
        } else if (popuptype == 'mail')
        {
            html +=
                "<div class='mailwin'><div class='head'>"
                + "<h1>" + Locale.MailFormHeading + "</h1>"
                + "<div style='text-transform: uppercase;font-size: 10px;margin-bottom: 5px;'>sales @ comptrade .com | exportsales @ comptrade .com</div>"
                + "</div>"
                + "<div id='mailwincontactform'>"
                + "<h1>" + Locale.MailFormContact + "</h1>"
                + "<div><div class='leftcol'>"
                + "<div class='row'><label>" + Locale.MailFormName + ":</label><input type='text' id='mailwinname' /></div>"
                + "<div class='row'><label>" + Locale.MailFormEmail + ":</label><input type='text' id='mailwinemail' /></div>"
                + "<div class='clear'></div>"
                + "</div>"
                + "<div class='rightcol'>"            
                + "<div class='row'><div style='float:left;width:80px;'>" + Locale.MailFormCompany + ":</div> <input type='text'  id='mailwincompany'/></div>"
                + "<div class='row'><div style='float:left;width:80px;' class='telephone'>" + Locale.MailFormTelephone + ":</div> <input type='text'  id='mailwintelephone'/></div>"
                + "<div class='clear'></div>"
                + "</div><div class='clear'></div></div>"  
                
                + "<h1>Meddelande</h1>"
                + "<div class='row'><div style='float:left;width:80px;'>" + Locale.MailFormSubject + ":</div> <input type='text' style='width:370px;'  id='mailwinsubject'/></div>"
                + "<div class='lastrow'><div style='float:left;width:80px;'>" + Locale.MailFormMessage + ":</div> <textarea style='width:370px;height:80px;' id='mailwinbody'></textarea></div>"
                + "<p align='right'><input type='button' class='button' value='" + Locale.MailFormSend + "' onclick='submitmailform();'/></p>"
                + "</div>"
            ;
        }
        else if (popuptype == 'call')
        {
            if (personalServiceOnline)
            {
                html +=
                      "<div class='callwin'>"
                    + "<img src='/Images/personalservice/maria-large.png' class='onlineperson' />"
                    + "<div class='head'>"
                    + "<a href='skype:callcomptrade?call' title='Call Comptrade'><img src='/Images/skype-call-large.gif' class='skype' /></a>"   
                    + "<h1>" + Locale.SpeakToSales + "</h1>"
                    + "<div class='onlinestatus'>" + Locale.OpeningHours + "</div>"
                    + "<div class='openinghours'>M-F 8.00-17.00 GMT+1</span></div></div>"
                    + "<h1>" + Locale.CallUs + "</h1>"
                    + "<p class='callustext'>" + Locale.CallUsText + "</p>"
                    + "<div class='leftcol'>"
                    + "<a href='skype:callcomptrade?call' title='Call Comptrade'><img src='/Images/skype-call-small.gif' class='skypecall' /></a>"              
                    + "<h2>" + Locale.Sales + "</h2>"               
                    + "<p><span class='telephone'>+46 300 690 650</span><br/>Fax  +46 300 690 651</p></div>"
                    + "<div class='rightcol'>"            
                    + "<a href='skype:callcomptrade?call' title='Call Comptrade'><img src='/Images/skype-call-small.gif' class='skypecall' /></a>"  
                    + "<h2>" + Locale.Export + "</h2>"
                    + "<p><span class='telephone'>+46 300 690 630</span><br/>Fax  +46 300 690 631</p></div>"  
                    + "<img src='/Images/skype-dark.gif' class='skypebottom' />"          
                    + "</div>"     
               ;
            }
            else
            {
                html +=
                      "<div class='callwin'>"
                    + "<img src='/Images/personalservice/maria-large.png' class='onlineperson' />"
                    + "<div class='head'>"
                    + "<h1>" + Locale.SpeakToSales + "</h1>"
                    + "<div class='onlinestatus'>" + Locale.OpeningHours + "</div>"
                    + "<div class='openinghours'>M-F 8.00-17.00 GMT+1</span></div></div>"
                    + "<h1>" + Locale.CallUs + "</h1>"
                    + "<p class='callustext'>" + Locale.CallUsText + "</p>"
                    + "<div class='leftcol'>"
                    + "<h2>" + Locale.Sales + "</h2>"               
                    + "<p><span class='telephone'>+46 300 690 650</span><br/>Fax  +46 300 690 651</p></div>"
                    + "<div class='rightcol'>"            
                    + "<h2>" + Locale.Export + "</h2>"
                    + "<p><span class='telephone'>+46 300 690 630</span><br/>Fax  +46 300 690 631</p></div>"  
                    + "<img src='/Images/skype-dark.gif' class='skypebottom' />"          
                    + "</div>"     
               ;            
            }
        }        
        
        popupwindow.innerHTML = html + "</div>" 
        
        window.addEvent("scroll", function() {
            scrollto = window.getScroll();
			popuproot.style.left = scrollto.x;
			popuproot.style.top = scrollto.y
			popupwindow.style.top = ((window.getHeight() - 400)/2).toInt() + "px";
			popupwindow.style.left = ((window.getWidth() - 520)/2).toInt() + "px";
        });
        window.addEvent('resize', function() {
        	popuproot.style.height = window.getScrollHeight() + 'px';
			popuproot.style.width = window.getScrollWidth() + 'px';
			popupwindow.style.top = ((window.getHeight() - 400)/2).toInt() + "px";
			popupwindow.style.left = ((window.getWidth() - 520)/2).toInt() + "px";

	    });
        
        document.body.appendChild(popuproot);
        document.body.appendChild(popupwindow);
    }
    function submitEnterChat()
    {
        chatName = $('chatName').value;
        chatCompany = $('chatCompany').value;

        $('chatRegister').style.display = 'none';
        $('chatConnecting').style.display = 'block';
        
        HardToFind.WS.SearchAutoComplete.EnterChat(chatName, chatCompany ,          
             enterChat_onMethodCompleted, enterChat_onMethodFailed, null );   
        $('chatInput').addEvent('keypress', function(event){
            if (event.code == 13)
            {
                submitSendChatMessage();
                return false;
            }
        });  
    }
    function submitSendChatMessage()
    {
        msg = $('chatInput').value;
        sendChatMessage(msg);
        $('chatInput').value = "";    
    }
    function chatConnectionClosedUnexpected()
    {
        chatAppend("Lost connection.");
    }
    
    function submitmailform()
    {
        name =  $('mailwinname').value;
        company =  $('mailwincompany').value;
        email =  $('mailwinemail').value;
        telephone =  $('mailwintelephone').value;
        subject =  $('mailwinsubject').value;
        body =  $('mailwinbody').value;
        $('mailwincontactform').innerHTML = 
            "<div class='mailwinsent'>" + Locale.SendingMail + "</div>";
        HardToFind.WS.MailServices.SendContactForm(name, company, email, telephone, subject, body);
        $('mailwincontactform').innerHTML = 
            "<div class='mailwinsent'><h1>" + Locale.MailSentHeading + "</h1>" + Locale.MailSentText + "</div>";
    }
    
