﻿/* rounded borders - varying radii, "all" browsers */
DD_roundies.addRule('.CategorySelected', '5px', true);
DD_roundies.addRule('.SubCategorySelected', '5px', true);

// ajax history initialisation
window.dhtmlHistory.create({
    debugMode: false,
    toJSON: function(o) {
        return JSON.stringify(o);
    }
    , fromJSON: function(s) {
        return JSON.parse(s);
    }
});

// Listener fires when the hash value changes through use of back/forward browser buttons
var yourListener = function(newLocation, historyData) {
    if (OnSearchPage) {
        SearchMediaByHashValue();
    }
    if (OnViewMediaPage) {
        ViewMediaByHashValue();
    }
}


// Main onload function that is called whenever any page on the site loads
window.onload = function() {
    // Call function to add custom form elements here as the window.onload function in the js file is overridden by the one here
    Custom.init();
    // Tabber stuff
    tabberAutomatic();
    tabberAutomaticOnLoad();

    // Update Watermark textboxes
    if (LoginUserNameTextBox.length > 1) {
        OnPageLoad(LoginUserNameTextBox, 'Enter Username');
    }
    if (LoginPasswordTextBox.length > 1) {
        OnPageLoad(LoginPasswordTextBox, '');
    }
    OnPageLoad(SearchTextBox, 'Enter Search Terms');

    // if on search page run search
    if (OnSearchPage) {
        if (window.location.hash.length > 1) {
            dhtmlHistory.add(window.location.hash, window.location.hash);
        }
        // Get categories list and update
        var URL = window.location.toString();
        UpdateCategories(URL);
        
        //alert('Running window.onload');
        SearchMediaByHashValue();
    }

    // if on view media page get media info
    if (OnViewMediaPage) {
        if (window.location.hash.length > 1) {
            dhtmlHistory.add(window.location.hash, window.location.hash);
        }
        ViewMediaByHashValue();
    }

    dhtmlHistory.initialize();
    dhtmlHistory.addListener(yourListener);
}


// Ajax search form functions - relates to Search.ascx

function btnSearch_Click_JS() {
    var SearchString = "";
    var SearchKeywords = true;
    var SearchDescription = true;
    var QueryString = "";
    //var Categoryid = 0;

    // Get values from search form
    SearchString = document.getElementById(SearchTextBox).value;
    if (document.getElementById(SearchKeywordsCheckBox).checked == false) {
        SearchKeywords = false;
    }
    if (document.getElementById(SearchDescriptionCheckBox).checked == false) {
        SearchDescription = false;
    }

    // if user typed in a number then go straight to asset page
    if (!isNaN(SearchString) && parseInt(SearchString) > 0) {
        if (OnViewMediaPage) {
            window.location.hash = "#?assetid=" + SearchString;
            dhtmlHistory.add("#?assetid=" + SearchString, "#?assetid=" + SearchString);
            ViewMediaByHashValue();
        }
        else {
            window.location.assign("/media/view/#?assetid=" + SearchString);
        }
    }

    // Else do a search
    else {
        // Construct QueryString
        if (SearchString != '' && SearchString != 'Enter Search Terms') {
            SearchString = URLDecode(SearchString).replace("+", " ");
            QueryString = "#?q=" + SearchString + "&searchkeywords=" + SearchKeywords + "&searchdescription=" + SearchDescription;
        }
        else {
            QueryString = "#?showall=1";
        }

        // If not on search page already then redirect to it with the Querystring set as the hashvalue of the page
        if (OnSearchPage) {
            var Url = window.location.toString();
            var QPortions = Url.split("?").length;
            var HPortions = Url.split("#").length;

            // check current querystring to avoid more than one question mark
            if (HPortions == 2 && Url.indexOf("#?") >= 0) {
                window.location.hash = QueryString;
                dhtmlHistory.add(QueryString, QueryString);
                SearchMediaByHashValue();
            }
            // if a regular querystring send the user to the search page with an ajax querystring
            else if (QPortions == 2 && HPortions == 1) {
                window.location.assign("/media/search/" + QueryString);
            }
            else if (QPortions == 1 && HPortions == 1) {
                window.location.hash = "#?showall=1";
                dhtmlHistory.add(QueryString, QueryString);
                SearchMediaByHashValue();
            }
        }
        else {
            document.location.assign("/media/search/" + QueryString);
        }
    }
}

// This may now be redundant
function UpdateSearchBox(element, SearchString) {
    //document.getElementById(element).value = URLDecode(SearchString).replace("+", " "); ;
    //document.getElementById(element).className = "ClearWatermark";
}

function URLDecode(encodedString) {
    var output = encodedString;
    var binVal, thisString;
    var myregexp = /(%[^%]{2})/;
    while ((match = myregexp.exec(output)) != null
                 && match.length > 1
                 && match[1] != '') {
        binVal = parseInt(match[1].substr(1), 16);
        thisString = String.fromCharCode(binVal);
        output = output.replace(match[1], thisString);
    }
    return output;
}



// Ajax search results functions - relates to SearchResults.ascx

function SearchMediaByHashValue() {
    // Use window.location instead of window.location.hash because IE6 doesn't like question marks in the hash value, and the Querystring code library works with full URLs
    var URL = window.location.toString();
    // insert some logic here to deal with querystring AND hash being empty - do searchall=1 - still needed? yes
    var URLElements = URL.split('#');
    var SearchString = '#' + URLElements[1];
    // call function to update categories list
    UpdateCategories(URL);
    // only call search function if hash value has something in it
    if (SearchString.length > 1 && SearchString != '#undefined') {
        onAjaxBegin('SearchResultsPanel', 'SearchResultsPanelLoading');
        // function SearchAssetsWeb defined in AssetWebServices.asmx.cs, enabled for page access using script proxy class
        // still calling search function twice on following paging links
        GuernseyImageLibrary.Web.webservices.AssetWebServices.SearchAssetsWeb(URL, onSearchSucceeded, onSearchFailed);
        // put search query back in the search textbox (if there was one)
        var SearchElements = SearchString.substr(2).split('&');
        for (var i in SearchElements) {
            var element = SearchElements[i].split('=');
            if (element[0] == 'q' && element[1].length > 0) {
                UpdateSearchBox(SearchTextBox, element[1]);
            }
        }
    }
}

function onSearchSucceeded(result, userContext, methodName) {
    var randomnumber = Math.floor(Math.random() * 10000)
    var searchdata = result[0] + "<img src=\"/usercontrols/EmptyImage.aspx?" + randomnumber + "\" onload=\"onAjaxComplete('SearchResultsPanel', 'SearchResultsPanel');\" />";
    var numberofresults = result[1];
    var paginglinks = result[2];
    $get('SearchResultsData').innerHTML = searchdata;
    $get('SearchResultsNumber').innerHTML = numberofresults;
    $get('SearchResultsPaging').innerHTML = paginglinks;
    $get('SearchResultsPagingBottom').innerHTML = paginglinks;
}

function onSearchFailed(error, userContext, methodName) {
    alert("An error occurred: " + error.get_message());
}

// called when a user clicks a paging link on the search page
function FollowSearchLink(QueryString) {
    // If not on search page already then redirect to it with the Querystring set as the hashvalue of the page
    if (OnSearchPage) {
        var Url = window.location.toString();
        var QPortions = Url.split("?").length;
        var HPortions = Url.split("#").length;
        
        // check current querystring to avoid more than one question mark
        if (HPortions == 2 && Url.indexOf("#?") >= 0) {
            window.location.hash = QueryString;
            dhtmlHistory.add(QueryString, QueryString);
            SearchMediaByHashValue();
        }
        // if a regular querystring send the user to the search page with an ajax querystring
        else if (QPortions == 2 && HPortions == 1) {
            window.location.assign("/media/search/" + QueryString);
        }
        else if (QPortions == 1 && HPortions == 1) {
            window.location.hash = "#?showall=1";
            dhtmlHistory.add(QueryString, QueryString);
            SearchMediaByHashValue();
        }
    }
    else {
        window.location.assign("/media/search/" + QueryString);
    }
}



// Ajax view media functions - relates to /media/view/Default.aspx

function ViewMediaByHashValue() {
    var URL = window.location.toString();
    var URLElements = URL.split('#');
    var QueryString = '#' + URLElements[1];
    // only call search function if hash value has something in it
    if (QueryString.length > 1 && QueryString != '#undefined') {
        onAjaxBegin('MediaPanel', 'MediaPanelLoading');
        GuernseyImageLibrary.Web.webservices.AssetWebServices.ViewAssetWeb(URL, onMediaSucceeded, onMediaFailed);
        // function ViewAssetWeb defined in AssetWebServices.asmx.cs, enabled for page access using script proxy class
    }
}

function onMediaSucceeded(result, userContext, methodName) {
    var randomnumber = Math.floor(Math.random() * 10000)
    var assettitle = result[0] + "<img src=\"/usercontrols/EmptyImage.aspx?" + randomnumber + "\" onload=\"onAjaxComplete('MediaPanel', 'MediaPanel');\" />";
    //var assetimage = result[0] + "<img src=\"/images/empty.gif\" onload=\"onAjaxComplete('MediaPanel', 'MediaPanel');\" />";
    var assetinfo = result[1];
    var relatedassets = result[2];
    $get('MediaTitle').innerHTML = assettitle;
    $get('MediaItem').innerHTML = assetinfo;
    //$get('RelatedMedia').innerHTML = relatedassets;
}

function onMediaFailed(error, userContext, methodName) {
    alert("An error occurred: " + error.get_message());
}

// Called when a user clicks a link on the search page or a related image link on the asset page
function FollowMediaLink(assetid) {
    var QueryString = "";

    // Construct QueryString
    QueryString = "#?assetid=" + assetid;

    // If not on search page already then redirect to it with the Querystring set as the hashvalue of the page
    if (OnViewMediaPage) {
        window.location.hash = QueryString;
        dhtmlHistory.add(QueryString, QueryString);
        ViewMediaByHashValue();
    }
    else {
        document.location.assign("/media/view/" + QueryString);
    }
}        
        


// Ajax categories functions - relates to Categories.ascx

function UpdateCategories(URL) {
    GuernseyImageLibrary.Web.webservices.CategoryWebServices.UpdateCategories(URL, onCategoriesSucceeded, onCategoriesFailed);
}

function onCategoriesSucceeded(result, userContext, methodName) {
    var categoriesdata = result;
    $get('Categories').innerHTML = categoriesdata;
}

function onCategoriesFailed(error, userContext, methodName) {
    alert("An error occurred: " + error.get_message());
}



// Style switching for ajax loader

/*function setOpacity(element, value) {
    document.getElementById(element).style.opacity = value / 10;
    document.getElementById(element).style.filter = 'alpha(opacity=' + value * 10 + ')';
}*/

function onAjaxBegin(element, loadingclass) {
    document.getElementById('SearchAnimationPanel').className = 'SearchAnimationPanelActive';
    document.getElementById(element).className = loadingclass;
}

function onAjaxComplete(element, finishedclass) {
    document.getElementById('SearchAnimationPanel').className = 'SearchAnimationPanel';
    document.getElementById(element).className = finishedclass;
}


// LightBox methods

function addLightBoxMedia(MediaId) {
    GuernseyImageLibrary.Web.webservices.AssetWebServices.InsertLightBoxAssetWeb(MediaId, onAddLightBoxMediaSucceeded, onAddLightBoxMediaFailed);
}

function onAddLightBoxMediaSucceeded(result, userContext, methodName) {
    if (parseInt(result) > 0) {
        $('#SearchResultsUpdateMsg').stop(true);
        $('#SearchResultsUpdateMsg').html("Added media " + result + " to your LightBox - <a href=\"/account/lightbox/\">View Lightbox</a>");
        $('#SearchResultsUpdateMsg').fadeTo(600, 1);
        $('#SearchResultsUpdateMsg').fadeTo(3000, 1);
        $('#SearchResultsUpdateMsg').fadeTo(600, 0, function() { $('#SearchResultsUpdateMsg').html("&nbsp;"); });
    }
    else {
        $('#SearchResultsUpdateMsg').stop(true);
        $('#SearchResultsUpdateMsg').html("Could not add media to your LightBox - it may already be added or your LightBox may be full");
        $('#SearchResultsUpdateMsg').fadeTo(600, 1);
        $('#SearchResultsUpdateMsg').fadeTo(3000, 1);
        $('#SearchResultsUpdateMsg').fadeTo(600, 0, function() { $('#SearchResultsUpdateMsg').html("&nbsp;"); });
    }
}

function onAddLightBoxMediaFailed(error, userContext, methodName) {
    $('#SearchResultsUpdateMsg').stop(true);
    $('#SearchResultsUpdateMsg').html("Error: could not add media to your LightBox");
    $('#SearchResultsUpdateMsg').fadeTo(600, 1);
    $('#SearchResultsUpdateMsg').fadeTo(3000, 1);
    $('#SearchResultsUpdateMsg').fadeTo(600, 0, function() { $('#SearchResultsUpdateMsg').html("&nbsp;"); });
}