﻿jQuery.noConflict();
var $j = jQuery;

var isIE6 = false;
function configurePopups() {

    /* hijack click behaviour for links that have the classname 'popup' to open in a popup window */
    jQuery('a.popup').click(function(e) {
        var href = jQuery(this).attr("href");

        window.open(href, "popup", "width=500,height=700,resizable=yes,scrollbars=yes");
        e.preventDefault();
        e.stopPropogation();
    });

    /* hijack click behaviour for links that have the classname 'popup' to open in a popup window */
    jQuery('a.popupNoFurniture').click(function(e) {
        var href = jQuery(this).attr("href");

        if (href.indexOf('?') > -1) {
            href += "&showfurniture=false";
        }
        else {
            href += "?showfurniture=false"
        }

        window.open(href, "popup", "width=500,height=700,resizable=yes,scrollbars=yes");
        e.preventDefault();
        e.stopPropogation();
    });
}

String.format = function() {
    var s = arguments[0];
    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i + 1]);
    }

    return s;
}

function isdefined(variable) {
    return (typeof (window[variable]) == "undefined") ? false : true;
}

function flashClassOnElement(element, cssClass) {
    /// Applies a class to an element then sets a timer running to remove it
    /// Useful when you want temporarily draw attention to an element

    // Mark the slot as updated
    element.addClass(cssClass);

    // Remove the updated class after 1 seconds
    window.setTimeout(function() {
        jQuery(element).removeClass(cssClass);
    }, 1000);
}

function globalAjaxErrorCallback(XMLHttpRequest, textStatus, errorThrown) {
    alert('Nova Global Error Handler: ' + textStatus);
}

function escapeHtml(input) {
    if (input) {
        input = input.replace(/&/g, "&amp;");
        input = input.replace(/>/g, "&gt;");
        input = input.replace(/</g, "&lt;");
        input = input.replace(/"/g, "&quot;");
        input = input.replace(/'/g, "&#039;");
    } else {
        input = '';
    }
    return input;
}

function redirectToLoginPage() {
    if (coreResources.loginUrl) {
        window.location.href = coreResources.loginUrl;
    } else {
        alert('You must be logged in.');
    }
}

function trimToNearestWord(input, maxLength, trailingText) {
    if (!input || input.length == 0) { return ''; }
    var result = input;
    if (input.length > maxLength) {
        var cutoffPoint = maxLength;
        for (var i = maxLength; i > 0; i--) {
            if (new RegExp(/^\s+$/).test(input[i - 1])) {
                cutoffPoint = i - 1;
                break;
            }
        }
        result = input.substring(0, cutoffPoint) + trailingText;
    }
    return result;
}

// limit the number of characters allowed to be entered into a textbox. Useful for textarea
function limitTextboxChars(jQuerySelector, jQueryContext, limit) {

    var textbox = jQuery(jQuerySelector, jQueryContext);
    
    textbox.unbind('keyup');
    textbox.keyup(function() {
        var text = jQuery(this).val();
        var textlength = text.length;
        if (textlength > limit) {
            jQuery(this).val(text.substr(0, limit));
            return false;
        }
        return true;
    })
}

/********************************************************************************************
*
*   Top Navigation component
*
********************************************************************************************/

var topNavigation = function(o) {
    this.init(o);
}
jQuery.extend(topNavigation.prototype, {
    navigation: null,
    options: null,
    arrHoveredLis: new Array(),
    _multiLevelNav: false,

    init: function(o) {
        // Default configuration properties       
        var defaults = { clientsideNavPreview: true, childIndicators: true, dropdownNav: true };
        // Cache references to key DOM elements
        this.navigation = jQuery('#topNavigation');
        this.options = jQuery.extend({}, defaults, o || {});

        jQuery(this.navigation).removeClass('no-js');

        if (jQuery('#header.multiLevelNav').length > 0) {
            this._multiLevelNav = true;
        }

        if (this.options.clientsideNavPreview && this._multiLevelNav) {
            this._hookupClientSideNavPreview();
        }

        if (this.options.dropdownNav && this._multiLevelNav) {
            this._hookupDropdownNav();
        }

        if (this.options.childIndicators) {
            this._addChildIndicators();
        }
    },

    _removeHoveredLis: function() {
        for (var i = this.arrHoveredLis.length - 1; i >= 0; i--) {
            var li = this.arrHoveredLis[i];
            jQuery(li).removeClass("hover");
            this.arrHoveredLis.pop();
        }
    },

    _hookupClientSideNavPreview: function() {
        // Get all the level li elements
        // Hook em 'n Hide em wih HoverIntent rather than jQuery Hover because we want a delay on level1
        // http://cherne.net/brian/resources/jquery.hoverIntent.html

        var _self = this;

        jQuery('#topNavigation ul.level1 > li').hoverIntent({
            interval: 150,
            over: function() {
                _self._removeHoveredLis();
                jQuery(this).addClass('hover');
                _self.arrHoveredLis.push(this);
            },
            timeout: 500,
            out: function() {
            }
        });


        jQuery(this.navigation).hoverIntent({
            interval: 150,
            over: function() {
                jQuery('#topNavigation li.selected').addClass('override-selected').removeClass('selected');
            },
            timeout: 500,
            out: function() {
                // Reset to selected state upon leaving the Top navigation
                jQuery('li.override-selected', _self.navigation).each(function() {
                    jQuery(this).removeClass('override-selected').addClass('selected');
                    jQuery(this).removeClass('hover');
                })
                _self._removeHoveredLis();
            }
        });
    },

    _hookupDropdownNav: function() {
        var _self = this;

        jQuery('ul.level1 > li', this.navigation).hover(function() {
            if (jQuery.browser.msie) {
                // if msie, limit width of last ul if it goes beyond the right hand edge of the top level ul.
                var liLast = jQuery(this).children('ul.level2').children('li.last');
                if (liLast != null && liLast.length > 0) {
                    var topUl = jQuery('ul.level1', _self.navigation);
                    var topUlRight = topUl.offset().left + topUl.outerWidth(true);
                    var a = liLast.children('a');
                    var width = topUlRight - a.offset().left;
                    var ul = liLast.children('ul.level3');
                    var ulRight = a.offset().left + ul.outerWidth(true);
                    if (topUlRight < ulRight) {
                        ul.width(width);
                    }
                }
            }
        },
                                                        function() { }
        );

        // Note there is no delay opening items under level 2
        jQuery('ul.level2 > li:not(.leaf)', this.navigation).hover(
                                            function() {
                                                jQuery(this).addClass('hover');

                                            },
                                            function() {
                                                jQuery(this).removeClass('hover');
                                            }
                                                );

    },

    _addChildIndicators: function() {
        jQuery('li.hasChildren > a', this.navigation).each(function() {
            /* The way that the markup works is 
            
            <li>
                <a>
                <ul>
                </ul>
            </li>
            
            By checking that the anchor has some siblings we are checking there is a 
            child list (ul) of navigation items
                
            */
            
            if (jQuery(this).siblings().length > 0) {
                jQuery(this).append('<div class="navTreeItem-HasChildren"></div');
            }
        });
    }

});

if (!window.Nova) { window['Nova'] = {}; };
if (!window.Nova.Controls) { window['Nova']['Controls'] = {}; };
window['Nova']['Controls']['TopNavigation'] = topNavigation;

/********************************************************************************************
*
*   Favourites Toggle button
*
********************************************************************************************/

var favouritesToggle = function(o) {
    this.init(o);
}
jQuery.extend(favouritesToggle.prototype, {
    options: null,
    restApiPathFavourites: '/api/v1_1/favorites/{0}/{1}/{2}', /*favorites/{code}/{objectTypeId}/{objectId}*/

    init: function(o) {
        // Default configuration properties       
        var defaults = { confirmDelete: false };
        // Cache references to key DOM elements
        var buttons = jQuery('div.favourite');
        this.options = jQuery.extend({}, defaults, o || {});

        var _self = this;

        jQuery(buttons).find('button').click(function(event) {
            var favouriteData = JSON.parse(jQuery('.data', this.parentNode).val());
            var restUrl = String.format(_self.restApiPathFavourites, favouriteData.code, favouriteData.objectTypeId, favouriteData.objectId);
            var button = this;

            var onError = function(xhr, ajaxOptions, thrownError) {
                if (novaDebugMode) {
                    jQuery('body').html(xhr.responseText);
                } else {
                    redirectToLoginPage();
                }
            }

            if (!favouriteData.on) {
                jQuery.ajax({
                    type: 'POST',
                    url: restUrl,
                    data: {},
                    success: function(data) {
                        _self._toggleOnSuccess(button);
                    },
                    error: onError
                });
            }
            else {
                if (_self.options.confirmDelete === false || confirm(favouriteButton_languageResources[2])) {
                    jQuery.ajax({
                        type: 'DELETE',
                        url: restUrl,
                        success: function(data) {
                            _self._toggleOffSuccess(button);
                        },
                        error: onError
                    });
                }
            }

            event.preventDefault()
        });

    },

    _toggleOnSuccess: function(button) {
        // Toggling on the favourite was successful. Update the client side data flagging it as on.
        var favouriteData = JSON.parse(jQuery('.data', button.parentNode).val());
        favouriteData.on = true;

        // We are using the hidden field as a store for the data so whack it back in
        jQuery('.data', button.parentNode).val(JSON.stringify(favouriteData));
        jQuery(button)
                .val(favouriteButton_languageResources[0])
                .html('<span>' + favouriteButton_languageResources[0] + '</span>')
                .parent()
                .removeClass('favouriteOff')
                .addClass('favouriteOn')

        if (this.options.toggleOnSuccessCallback) {
            this.options.toggleOnSuccessCallback(button);
        }
    },

    _toggleOffSuccess: function(button) {

        // Toggling off the favourite was successful. Update the client side data flagging it as no longer on.
        var favouriteData = JSON.parse(jQuery('.data', button.parentNode).val());
        favouriteData.on = false;

        // We are using the hidden field as a store for the data so whack it back in
        jQuery('.data', button.parentNode).val(JSON.stringify(favouriteData));
        jQuery(button)
                .val(favouriteButton_languageResources[1])
                .html('<span>' + favouriteButton_languageResources[1] + '</span>')
                .parent()
                .removeClass('favouriteOn')
                .addClass('favouriteOff')

        if (this.options.toggleOffSuccessCallback) {
            this.options.toggleOffSuccessCallback(button);
        }
    }
});

if (!window.Nova) { window['Nova'] = {}; };
if (!window.Nova.Controls) { window['Nova']['Controls'] = {}; };
window['Nova']['Controls']['FavouritesToggle'] = favouritesToggle;

/********************************************************************************************
*
*   Link Tracking
*
********************************************************************************************/

var linkTracking = function(o) {
    this.init(o);
}
jQuery.extend(linkTracking.prototype, {
    options: null,
    restApiPathLinkTracking: '/api/v1_0/tracking/incrementTrackingLinkSummary',

    init: function(o) {
        // Default configuration properties       
        var defaults = {};

        // Cache references to key DOM elements
        this.options = jQuery.extend({}, defaults, o || {});

        var _self = this;

        jQuery('a.tracked').click(function(event) {
            var anchor = this;

            var bodyData = String.format('<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">{0}</string>', jQuery(anchor).text());

            jQuery.post(
                        _self.restApiPathLinkTracking,
                        bodyData,
                        function(data) {
                        },
                        "xml"
                        );
        });
    }
});

if (!window.Nova) { window['Nova'] = {}; };
if (!window.Nova.Modules) { window['Nova']['Modules'] = {}; };
window['Nova']['Modules']['LinkTracking'] = linkTracking;

jQuery(document).ready(function() {
    if ((jQuery.browser.msie) && (parseInt(jQuery.browser.version, 10) == "6")) {
        isIE6 = true;
        try {
            document.execCommand('BackgroundImageCache', false, true);
        }
        catch (e) {
        }
    }

    //Watermarking.
    jQuery('.value-replace').each(function() {
        var defaultValue = '';
        var keypressed = false;
        jQuery(this).focus(function() { if (defaultValue === '' && !keypressed) { defaultValue = jQuery(this).val(); jQuery(this)[0].value = ''; } });
        jQuery(this).blur(function() { if (jQuery(this).val() === '' && !keypressed) { jQuery(this)[0].value = defaultValue; defaultValue = ''; } });
        jQuery(this).keypress(function() { keypressed = true; });
        jQuery(this).change(function() { if (jQuery(this).val() === '') keypressed = false; });
    });

    configurePopups();
});
