/*********************************************************************
* Copyright 2009 Amblique :: www.amblique.com :: All Rights Reserved *
**********************************************************************/

$(function() {
    initialisePNGFix();
    initialiseFonts();
    initialiseOverlays();
    initialiseDefaultButtons();
    initialiseTooltips();
    initialiseTriggers();
    initialiseScrollables();
    initialiseBrowserBackLinks();
    checkForException();

    initialDebugStatements();
});

initialDebugStatements = function() {
    trace(document.location);
    trace(document.cookie);
};

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 { $('body').supersleight(); } catch (e) { trace(e); }
};

initialiseScrollables = function() {
    try {
        trace('initialiseScrollables');

        // vertical scrollables
        $('.v-auto-scrollable').scrollable({
            size: 3,
            vertical: true,
            clickable: false,
            loop: true,
            interval: 5000,
            onBeforeSeek: function() {
                this.getItems().fadeTo(300, 0.2);
            },
            onSeek: function() {
                this.getItems().fadeTo(300, 1);
            }
        });
    } catch (e) {
        trace(e);
    }
};

initialiseOverlays = function() {
    try {
        trace('initialiseOverlays');
        // default normal overlay
        $('a[rel=#overlay]').overlay({
    });

    // iframe overlays
    $('a[rel*=#iframe-overlay]').overlay({
        onBeforeLoad: function() {
            var iframe = (this.getContent().find('iframe').length > 0 ? this.getContent().find('iframe')[0] : undefined); trace(iframe);
            if (typeof iframe != 'undefined') {
                trace(this.getTrigger().attr('href'));
                iframe.src = this.getTrigger().attr('href');
            }
        }
    });
} catch (e) {
    trace(e);
}
};

initialiseFonts = function() {
    try {
        trace('initialiseFonts');
        Cufon.replace('.font,.contentText h2, .contentText h3, .form h3, .form h4, .contentDesignCentre .projectItem h3, .header-type-a .east h3, .header-type-b .east h4, h1.contentTitle, h2.contentTitle, h3.contentTitle, h4.contentTitle, .popupSuprePoints dl.balance dt, .elementMoreImages ul li.title, .contentHome .contentText1 h3, .scrollable .item .title', { hover: true });
    } catch (e) {
        // what?
    }
};

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);
                    }
                }
            }
            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', 'center']
                });
            }
        });
    } catch (e) {
        trace(e);
    }
}

initialiseDefaultButtons = function() {
    try {
        trace('initialiseDefaultButtons');

        var FORM_ID = '#' + $('form').attr('id');
        var DEFAULT_BUTTON_ATTRIBUTE = 'default';

        var KEY_EVENT_TO_TRACK = 'keypress';
        var MOUSE_EVENT_TO_TRIGGER = 'click';
        var SUBMIT_KEY_CODE = 13;

        $("input[" + DEFAULT_BUTTON_ATTRIBUTE + "]").each(function(i) {
            trace(this);
            $(this).unbind(KEY_EVENT_TO_TRACK).bind(KEY_EVENT_TO_TRACK, function(event) {
                trace(KEY_EVENT_TO_TRACK);
                try {
                    if (event.keyCode == SUBMIT_KEY_CODE) { // enter key detected
                        var returnCode = false;
                        if ($(this).attr(DEFAULT_BUTTON_ATTRIBUTE)) { // get the target element (default button)
                            var default_button_id = '#' + $(this).attr(DEFAULT_BUTTON_ATTRIBUTE);
                            if ($(default_button_id).length > 0) {
                                var default_button_type = $(default_button_id)[0].tagName;
                                if (/a/i.test(default_button_type)) { // this is an anchor button (link button)
                                    var href = $(default_button_id).attr('href');
                                    if (/javascript/i.test(href)) {
                                        var bubble = $(default_button_id).triggerHandler(MOUSE_EVENT_TO_TRIGGER);
                                        if (bubble || typeof bubble == 'undefined') returnCode = eval(href);
                                    }
                                } else if (/input/i.test(default_button_type)) { // this is an input button
                                    // need to clear jQuery validation object if present
                                    var form_id = '#' + $('form').attr('id');
                                    if ($.data($(form_id))) {
                                        $(form_id).validate().resetForm();
                                        $.removeData($(form_id));
                                    }
                                    returnCode = $(default_button_id).trigger(MOUSE_EVENT_TO_TRIGGER);
                                } else { // can't determine the type, so try clicking
                                    try { returnCode = $(default_button_id).trigger(MOUSE_EVENT_TO_TRIGGER); } catch (triggerexception) { trace(triggerexception); }
                                }
                            }
                        }
                        return false;
                    }
                } catch (keyexception) {
                    trace(keyexception);
                }
            });
        });
    } catch (e) {
        trace(e);
    }
}

trace = function(message) {
    var page = window.location; var hasConsole = false;
    try { if (typeof (console) != "undefined") hasConsole = true; } catch (e) { }
    if (hasConsole) { console.log(message); }
}

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 getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function ToggleClass(elementId, selectedCssClass, unselectedCssClass) {
    var element = document.getElementById(elementId);
    element.className = (element.className == selectedCssClass ? unselectedCssClass : selectedCssClass);
}

function pushEventTracking(category, subCategory, event) {
    if (_gaq != null) {
        var cat = "'" + category + "'";
        var subCat = "'" + subCategory + "'";
        var event = "'" + event + "'";
        _gaq.push(['_trackEvent', cat, subCat, event]);
    }
}

