/*********************************************************************
* Copyright 2010 Amblique :: www.amblique.com :: All Rights Reserved *
**********************************************************************/

trace = function(message) {
    if (message) {
        var hasConsole = false;
        try { if (typeof (console) != "undefined") hasConsole = true; } catch (e) { }
        if (hasConsole) { console.log(message); }
    }
}

$(function() {
    initialiseScrollables();
    //initialiseTabs();
    initialiseDefaultButtons();
    initialiseBrowserBackLinks();
    initialiseTooltips();
    initialiseTriggers();
    initialiseFlash();
    checkForException();
    initialiseOverlays();
    initialiseTruncateText();
    initialiseBindings();
});

initialiseBindings = function() {
    $("#lpbutton").click(function() {
        var _gaq = _gaq || [];
        _gaq.push(['_trackEvent', 'Liveperson', 'Click']);
    });
}

initialiseDefaultButtons = function() {
    try {
        var DEFAULT_SUBMIT_ATTRIBUTE = 'data-default';
        var DEFAULT_BUTTON_ATTRIBUTE = 'data-default-button';

        var KEY_EVENT_TO_TRACK = 'keydown';
        var KEY_EVENT_TO_IGNORE = 'keyup';
        var MOUSE_EVENT_TO_TRIGGER = 'click';
        var SUBMIT_KEY_CODE = 13;

        //check if any button on the form has been specified as the default click button. If there is, and it's not the button being clicked
        //stop propagation. This is to avoid duplicate button clicks with form default + actual intended button to be clicked.
        $('input[type=submit]').click(function(e) {
            var defaultClickButton = $('[' + DEFAULT_BUTTON_ATTRIBUTE + ']');
            if (defaultClickButton && defaultClickButton.length > 0 && !($(this).attr(DEFAULT_BUTTON_ATTRIBUTE))) {
                e.stopImmediatePropagation(); //intended button to be actioned wasn't this one, prevent this button's default action.
                return false;
            }
        });

        $('[' + DEFAULT_SUBMIT_ATTRIBUTE + ']').each(function(i) {

            $(this).bind(KEY_EVENT_TO_IGNORE, function(event) {
                return;
            });

            $(this).bind(KEY_EVENT_TO_TRACK, function(event) {
                try {
                    if (event.keyCode == SUBMIT_KEY_CODE) { // enter key detected
                        if ($(this).attr(DEFAULT_SUBMIT_ATTRIBUTE)) { // check if element has attribute of default linked button specified.
                            var $default_submit_attr = $('[' + $(this).attr(DEFAULT_SUBMIT_ATTRIBUTE) + ']');
                            if ($default_submit_attr.length > 0) { //does the default button referenced exist?
                                $('[' + DEFAULT_BUTTON_ATTRIBUTE + ']').removeAttr(DEFAULT_BUTTON_ATTRIBUTE); //clear all buttons with the default attribute
                                $default_submit_attr.attr(DEFAULT_BUTTON_ATTRIBUTE, 'true'); //only set the intended button to have the default attribute
                                if ($default_submit_attr[0].onclick && $default_submit_attr[0].onclick.toString().indexOf('Ajax') >= 0)
                                {
                                    //if an AJAX event is already bound to the regular click event for the button, stop JQuery click() functionality defining
                                    //its own additional functionality as it will cause postback and callback. Only want the button to do the AJAX onclick.
                                    $default_submit_attr.click(function(e) {
                                        e.stopImmediatePropagation();
                                        return false;
                                    });
                                }
                                $default_submit_attr.click(); //click the button
                                event.stopPropagation(); //stop normal propagation of the keyup event
                            }
                        }
                    }
                }
                catch (keyexception) {
                    trace(keyexception);
                }
            });
        });

        trace('default buttons bound');

    } catch (e) {
        trace(e);
    }
}


// Truncate text on 
initialiseTruncateText = function() {
    try {
            
     var    $LongDescription = $('.ProductDetails .description.description-long'),
            $LongDescriptionWrapper = $LongDescription.find('.description-wrapper'),
            $LongDescriptionMoreButton = $LongDescription.find('.btn.btn-e'),
            originalHeight = $LongDescriptionWrapper.height(),
            truncationHeight = 51; // set trunctation height here

    $LongDescriptionMoreButton
        .hide()


     if ( originalHeight >= truncationHeight ) {
             trace('original height ' + originalHeight);
             $LongDescriptionWrapper
                .height(50);
            
            $LongDescriptionMoreButton
                .show()
                .click(function (e) {
                    e.preventDefault();
                    trace('click e click e');
                    
                    $LongDescriptionWrapper
                        .height(originalHeight)
                        
                    $(this).hide();
                    
                });   
     
        
     }
     

        
        
    } catch (e) {
        trace(e);
    }
};

// Close the current overlay..
closeOverlays = function() {
    $(document).click();

    /* close opener */
    try {
        if (window && window.opener && window.opener.closeOverlays && window.opener != window) {
            window.opener.closeOverlays();
            return;
        }
    } catch (e) {
        trace(e);
    }

    /* close parent */
    try {
        if (window && window.parent && window.parent.closeOverlays && window != window.parent) {
            window.parent.closeOverlays();
        }
    } catch (e) {
        trace(e);
    }

    // Every page should have a hidden update cart button
    if ($('#btnRemoteUpdateCart').length > 0) $('#btnRemoteUpdateCart').click();
};

viewCartFromOverlay = function(varLocation) {

    //$(document).click();

    window.location = varLocation;
};

initialiseFormLabels = function() {
    try {
        $("input, textarea").labelify({
            labelledClass: 'labelled'
        });
    } catch (e) {
        trace(e);
    }
};

initialiseFlash = function() {
/*
    $('[flashsrc]').each(function(i) {
        var $this = $(this);
        var id = $this.attr('id'); trace(id);
        var flashsrc = $this.attr('flashsrc'); trace(flashsrc);
        flashembed(id, flashsrc);
    });
 */   
};

initialiseAnchorTargets = function() {
    $('a[target=_blank]').live('click', function(event) {
        if (!event) event = window.event;
        if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
        else {
            var newWindow = window.open($(this).attr('href'), '_blank');
            if (newWindow) {
                newWindow.focus();
                return false;
            }

            return true;
        }
    });
};
initialiseClickProtection = function() {
    $('a[href=#], a.script').live('click', function(event) {
        return false;
    });
};

initialiseBrowserBackLinks = function() {
    $('.browser-back').live('click', function(event) {
        window.history.back(); return false;
    });
};

checkForException = function() {
    // see if exception was found
    var hasErrors = false;
    try {
        if (typeof Exception != 'undefined') {
            alert(Exception);
            hasErrors = !hasErrors;
            Exception = undefined;
        }
    } catch (e) {
        trace(e);
    }
    return hasErrors;
};

initialisePNGFix = function() {
    try {
        // use DD_belatedPNG 0.0.8a
        if (typeof DD_belatedPNG != 'undefined' && DD_belatedPNG && DD_belatedPNG.fix) DD_belatedPNG.fix('#container');
    } catch (e) {
        trace(e);
    }
};

scrollToTop = function() {
    try { $('html, body').animate({ scrollTop: 0 }, 'slow'); } catch (e) { trace(e); }
};

initialiseOverlays = function() {
    var overlaySpeed = 'fast';
    try {
        /* normal overlays - where content is pre-populated */
        $('a[rel^=#overlay]').each(function(i) {
            $(this).overlay({ mask: '#000', speed: overlaySpeed });
        });

        /* iframe overlays - where content is loaded dynamically from the a.href */
        $('a[rel^=#iframeOverlay]').each(function(i) {
            try {
                $(this).overlay({
                    mask: '#000',
                    oneInstance: false,
                    speed: overlaySpeed,
                    onBeforeLoad: function() {
                        /* find the iframe */
                        var iframe = this.getOverlay().find('iframe');
                        var href = this.getTrigger().attr('href');
                        iframe.get(0).src = href;
                    },
                    onClose: function() {
                    var iframe = (this.getOverlay().find('iframe').length > 0 ? this.getOverlay().find('iframe')[0] : undefined); trace(iframe);
                        if (typeof iframe != 'undefined') {
                            iframe.src = '';
                        }
                    }
                });
            } catch (e) {
                trace(e);
            }
        });
    } catch (e) {
        trace(e);
    }

//    /* close buttons */
//    $('body').delegate('.close-overlay', 'click', function(event) {
//        if (typeof closeOverlays == 'function') {
//            closeOverlays();
//        }
//    });
};

initialiseFonts = function() {
    try {
        Cufon.replace('.font, h2.contentTitle, .brands-menu ul.sf-menu li.item a.link span, .DefusedLight-Red, .DefusedLight-LightGrey, .DefusedLight-DarkGrey', { fontFamily: 'DefusedLight' });
        Cufon.replace('.font-b', { fontFamily: 'DefusedRegular' });
    } catch (e) {
        trace(e);
    }
};

initialiseTriggers = function() {
    //trace('initialiseTriggers');

    var TRIGGER_CLASS = '.hastrigger';
    var TRIGGER_TARGET_ATTR = 'triggers';
    var MOUSE_EVENT_TO_TRIGGER = 'click';

    $(TRIGGER_CLASS).each(function(i) {
        $(this).bind(MOUSE_EVENT_TO_TRIGGER, function(event) {
            var trigger_id = $(this).attr(TRIGGER_TARGET_ATTR);
            var returnCode = false;
            if (typeof trigger_id != 'undefined' && trigger_id !== null) {
                if ($(trigger_id).length > 0) {
                    var href = $(trigger_id).attr('href');
                    var bubble = $(trigger_id).triggerHandler(MOUSE_EVENT_TO_TRIGGER); //trace(bubble);
                    if ((typeof bubble == 'undefined' || bubble) && (typeof href != 'undefined' && /javascript/i.test(href))) {
                        returnCode = eval(href);

                        // SUPRE SPECIFIC
                        $(TRIGGER_CLASS).removeClass('selected');
                        $(this).addClass('selected');
                    }
                }
            }
            return false;
        });
    });
}

initialiseTooltips = function() {
    try {
        trace('initialiseTooltips');

        var TOOLTIP_CLASS = '.tipenabled';
        var TOOLTIP_TARGET_ATTR = 'tiptarget';

        $(TOOLTIP_CLASS).each(function(i) {
            //trace(i);
            var target_id = $(this).attr(TOOLTIP_TARGET_ATTR);
            if (typeof target_id != 'undefined') {
                //trace(this); trace(target_id);
                $(this).tooltip({
                    tip: target_id,
                    delay: 0,
                    effect: 'toggle',
                    position: 'bottom right',
                    relative: true
                });
            }
        });
    } catch (e) {
        trace(e);
    }
}

function checkDefaultButton(defaultButtonAttribute) {   
    if ($('[' + defaultButtonAttribute + ']').length > 0) {
        $('[' + defaultButtonAttribute + ']').click();
        returnDefaultBehaviour = false;
    }
    return returnDefaultBehaviour;
}

/* HTML5 based initialisations */
initialiseScrollables = function(selector) {
    try {
        /* default scrollable config */
        var config = {
            selector: selector || '[class^=html5-scrollable]',
            defaults: {
                easing: jQuery.easing.easeInOutExpo ? 'easeInOutExpo' : 'swing',
                speed: 500,
                autoscroll: false,
                navigator: false,
                circular: false,
                autoplay: false,
                autopause: false,
                vertical: false
            }
        };

        $(config.selector).each(function(index) {
            try {
                trace('initialising html5 scrollable at index: {0}'.format(index));

                /* get scrollable options using HTML5 dataset */
                var $this = $(this);
                var options = $this.dataset();

                /* set some defaults */
                options.circular = options.circular === undefined ? config.defaults.circular : options.circular === 'true';
                options.autoplay = options.autoplay === undefined ? config.defaults.autoplay : options.autoplay === 'true';
                options.autopause = options.autopause === undefined ? config.defaults.autopause : options.autopause === 'true';
                options.vertical = options.vertical === undefined ? config.defaults.vertical : options.vertical === 'true';
                options.easing = options.easing === undefined ? config.defaults.easing : options.easing;
                options.speed = options.vertical === undefined ? config.defaults.speed : options.speed;
                options.autoscroll = options.autoscroll === undefined ? config.defaults.autoscroll : options.autoscroll === 'true';
                options.navigator = options.navigator === undefined ? config.defaults.navigator : options.navigator === 'true';

                trace(options);

                /* instantiate scrollable */
                $this.scrollable(options);
                trace($this);

                /* enable navigator plugin */
                if (options.navigator && $this.navigator)
                    $this.navigator(options);

                /* enable autoscroll plugin */
                if (options.autoscroll && $this.autoscroll)
                    $this.autoscroll(options);
            } catch (se) {
                trace(se);
            }
        });
    } catch (e) {
        trace(e);
    }
};

var mapFunction = function(options, option, api) {
    if (options === undefined || option === undefined || options[option] === undefined) return;
    if ($.isFunction(fn = window[options[option]])) options[api] = fn;
};

// Creates a toggle open/close slider for <dl> type lists.
toggleInfo = function(targetInfoWindow) {
    $(targetInfoWindow).slideToggle('slow', function() {

        $(targetInfoWindow).parent('dl').toggleClass('active');

    });
};

// limit the amount of characters that can be added to a control
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}

toggleFilterList = function(targetHiddenList, hrefItem) {
    if ($(hrefItem).html() == 'more...')
        $(hrefItem).html('less');
    else
        $(hrefItem).html('more...');
    $(targetHiddenList).slideToggle('slow');
};

initialiseProductDetailTabs = function() {
    $("ul.tabs").tabs("div.panes div.tab-content");
}
initialiseTabs = function(selector) {
    try {
        /* default tabs config */
        var config = {
            selector: selector || '[class^=html5-tabs]',
            defaults: {
                panes: '.html5-tab-pane',
                effect: 'slide',
                initialIndex: null
            }
        };

        $(config.selector).each(function(index) {
            try {
                trace('initialising html5 tabs at index: {0}'.format(index));

                /* get scrollable options using HTML5 dataset */
                var $this = $(this);
                var options = $this.dataset();

                /* TODO: set some defaults */
                options.effect = options.effect === undefined ? config.defaults.effect : options.effect;
                options.initialIndex = options.initialindex === undefined ? config.defaults.initialIndex : parseInt(options.initialindex, 0);

                /* map some functions */
                var events = ['onBeforeClick', 'onClick'];
                for (var i = 0; i < events.length; i++) {
                    var eventName = events[i];
                    mapFunction(options, eventName.toLowerCase(), eventName);
                }

                /* config based on options */
                options.panes = options.panes || config.defaults.panes;

                /* instantiate tabs */
                $this.tabs(config.selector + ' ' + options.panes, options);
            } catch (te) {
                trace(te);
            }
        });
    } catch (e) {
        trace(e);
    }
};
function changeDefaultButton(elementID) {
    document.forms[0].onkeypress = new Function("{return WebForm_FireDefaultButton(event, '" + elementID + "')}");    
}

function fireElement(objID) 
{

    var target=document.getElementById(objID);
    if(document.dispatchEvent) 
    { // W3C
        var oEvent = document.createEvent("MouseEvents");
        oEvent.initMouseEvent("click", true, true,window, 1, 1, 1, 1, 1, false, false, false, false, 0, target);
        target.dispatchEvent(oEvent);
    }
    else if(document.fireEvent) 
    { // IE
    target.fireEvent("onclick");
    }
}

function WebForm_FireDefaultButton(event, target) {

    if (!__defaultFired && event.keyCode == 13 && !(event.srcElement && (event.srcElement.tagName.toLowerCase()== "textarea"))) {
        var defaultButton;
        if (__nonMSDOMBrowser)
            defaultButton = document.getElementById(target);
        else
            defaultButton = document.all[target];

        if (typeof (defaultButton.click) != "undefined") {
            __defaultFired = true;
            defaultButton.click();
            event.cancelBubble = true;

            if (event.stopPropagation) event.stopPropagation();
            return false;
        }

        if (typeof (defaultButton.href) != "undefined") {
            __defaultFired = true;
            eval(defaultButton.href.substr(11));
            event.cancelBubble = true;

            if (event.stopPropagation) event.stopPropagation();
            return false;
        }

    }
    return true;
}


