var MatchUpdated = "";
var taggedTrackId = "";
var taggedStreamId = "";
var MatchResult =
{
    MatchFound: 0,
    NoMatch: 1
}
var animationRate = 600;

function updateStatusMessage(e,show,msg,CSSClass,rate) {
    if (!rate) { rate=animationRate; }
    if (!CSSClass) { CSSClass=''; }
    if (e[0]) {
        e.attr('class','');
        if (show) {
            if (msg) {
                e.html(msg).addClass(CSSClass).fadeIn(rate);
            }
        } else { //hide
            e.html('').fadeOut(rate);
        }
    }
}

function MatchShowAdvanced() {
    jQuery('#matchBasicSearch').fadeOut(animationRate, function(){
        jQuery('#matchAdvancedSearch').fadeIn(animationRate);
    });
}

function MatchShowBasic() {
    jQuery('#matchAdvancedSearch').fadeOut(animationRate, function(){
        jQuery('#matchBasicSearch').fadeIn(animationRate);
    });
}


function NoMatchFound() {
    var eleStatusMessage = jQuery("#matchStatusMessage");
    var iTMSSongID = -1;
    var statusID = 4;

    eleStatusMessage.hide();

    UpdateSelectedMatch(MatchResult.NoMatch, iTMSSongID);

}


function UpdateSelectedMatch(matchResult, trackName) {
    varType = "POST";
    switch (Number(matchResult)) {
        case MatchResult.MatchFound:
    
            
                window.location = "http://www.catamarans.com/sales/SearchV2.aspx?action=search&Terms=" + trackName;
            
            break;
    
        case MatchResult.NoMatch:
            varUrl = "/AutoSuggest/Handler/GetSearchResults.ashx?behavior=UPDATEMATCH&result=NOMATCH&taggedTrackID=" + taggedTrackID;
            break;
    }

}

function ServiceSucceeded(result) {//When service call is sucessful

    CheckIfASHXHandlerRedirectedToLoginPage(result);
    
    if (result == "Succeeded")
        MatchUpdated = true;
    else
        MatchUpdated = false;
}

function ServiceFailed(result) {
    MatchUpdated = false;
}



function GenerateDataTableRow(track, artist, album,iTMSSongID, popularity) {
    var row = "<tr ITMSSongID='" + iTMSSongID + "'>" +
                "<td class='colPrimary colTrack'>" + track + "</td>" + 
                "<td class='colArtist'>"+ artist +"</td>" + 
                "<td class='colAlbum'>" + album + "</td>"+  
                "<td class='colPopularity'><div class='pctgBar'><span class='pctg pctg" + popularity + "' style='width: " + popularity + "%;'>" + popularity + "</span></div></td>" +
              "</tr>";
    return row;
}

function IsUserAuthenticated() {

    var varUrl = "/AutoSuggest/Handler/GetSearchResults.ashx";

    jQuery.ajax({
        type: "GET", //GET or POST or PUT or DELETE verb
        url: varUrl, // Location of the service
        dataType: "json", //Expected data format from server
        processdata: true, //True or False
        success: function(msg) {//On Successfull service call
            CheckIfASHXHandlerRedirectedToLoginPage(msg);
        },
        error: function(msg) {// When Service call fails
            CheckIfASHXHandlerRedirectedToLoginPage(msg.responseText); 
         } 
    });
    
}

function   CheckIfASHXHandlerRedirectedToLoginPage(result) {

    if (result != null && result != "undefined" && typeof (result) != "object" && result.indexOf("action=\"Login.aspx?ReturnUrl") != -1) {
            alert("Your session has timed out.  Please login again.");
            window.location = "login.aspx";
            return;
        }
}

function setAutoSuggest() {
    var eleStatusMessage = jQuery("#matchStatusMessage");
    var iTMSSongID;
    var statusID;
    var itemID;

    eleStatusMessage.hide();

    jQuery("#autosuggest").autoSuggest("/AutoSuggest/Handler/GetSearchResults.ashx?behavior=GetMatchingSong", {
        selectedItemProp: "name",
        searchObjProps: "name",
        minChars: 2,
        //retrieveLimit: 20,
        neverSubmit: true,
        selectionAdded: function (elem) {
            MatchUpdated = false;

            iTMSSongID = jQuery("#TrackLookup_iTMSSongID").html();
            itemID = jQuery("#ItemID").html();

            if (itemID == "-1111")
                window.location = "http://www.catamarans.com/sales/SearchV2.aspx?action=search&Terms=";
            else if (itemID == "-1112") {
                window.location = "http://www.catamarans.com/sales/SearchV2.aspx?action=search&Terms=" + jQuery("#SearchString").html();
            }
            else {
                statusID = 3;
                UpdateSelectedMatch(MatchResult.MatchFound, iTMSSongID);
            }
        },
        selectionRemoved: function (elem) {
            elem.remove()
            updateStatusMessage(eleStatusMessage, false, '', '', 0);
        },
        beforeRetrieve: function (string) {
            updateStatusMessage(eleStatusMessage, true, ' ', 'resultsLoading', 0);
            return string;
        },
        retrieveComplete: function (data) {
            updateStatusMessage(eleStatusMessage, false, '', '', 0);
            return data;
        }

    });

}

jQuery('#matchPane').click(function () { flag = true; });

jQuery('#matchPane').blur(function () {
    // So long you didn't click div.stop, then
    if (!flag)
        jQuery('div .as-results').hide();
});

$(document).keyup(function (e) {
    if (e.keyCode == 27) { jQuery('.as-list').hide(); }
    else { jQuery('.as-list').show(); }   // esc
});

$(document).ready(function () {
    jQuery('#redirect').hide();
    jQuery('#CharterSearch').attr('checked', false);
    jQuery('#ForSaleSearch').attr('checked', true);
});

function RedirectToCharterSearchPage() {
    //jQuery('#redirect').css({ 'display': 'block' });
    jQuery('#CharterSearch').attr('checked', false);
    jQuery('#ForSaleSearch').attr('checked', true);

//    $('#screen').css({ opacity: 0.7, 'width': $(document).width(), 'height': $(document).height() });
    jQuery('#redirect').fadeIn(1000, function () {
        setTimeout("self.location='http://www.catamarans.com/charter/search.aspx'", 800)
    });
    //jQuery('#redirect').show(function () { window.location = 'http://www.catamarans.com/charter/search.aspx'; });

    return false;
}
