/*********************************************************************
* Copyright 2010 Amblique :: www.amblique.com :: All Rights Reserved *
**********************************************************************/

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() {
    initialiseOverlays();
    initialiseDefaultButtons();
    initialiseBrowserBackLinks();

    initialiseTooltips();
    initialiseTriggers();
    initialiseScrollables();

    initialiseFlash();

    initialisePopups();

    checkForException();
});

// 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);
    }
};


initialiseFormLabels = function() {
    try {
        $("input, textarea").labelify({
            labelledClass: 'labelled'
        });
    } catch (e) {
        trace(e);
    }
};

initialiseFlash = function() {
    $('[flashsrc]').each(function(i) {
        var $this = $(this);
        var flashsrc = $this.attr('flashsrc');
        if (flashsrc) flashembed($(this).attr('id'), { src: flashsrc, version: [9, 0], wmode: "transparent", allowfullscreen: false });
    });
};

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); }
};

initialiseScrollables = function() {
    try {
        // 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 {
        // default normal overlay
        $('a[rel=#overlay]').overlay({
            expose: '#000000'
        });

        // iframe overlays
        $('a[rel*=#iframe-overlay],input[rel*=#iframe-overlay]').overlay({
            expose: '#000000',
            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');
                }
            }
        });

        // close buttons
        $('.close-overlay').bind('click', function(event) {
            if (closeOverlays) 
                closeOverlays();
        });
    } catch (e) {
        trace(e);
    }
};

/// to use this:
/// <a href="www.google.com" data-width="600" data-height="400" data-name="WishListPrint" data-status="0" data-toolbar="0" data-rel="popup">Hello</a>
initialisePopups = function() {
    $('[data-rel=popup]').live('click', function(event) {
        var width = $(this).attr('data-width');
        var height = $(this).attr('data-height');
        var href = $(this).attr('href');
        var dataHref = $(this).attr('data-href');
        var name = $(this).attr('data-name');
        var status = $(this).attr('data-status');
        var toolbar = $(this).attr('data-toolbar');

        if (!href && dataHref)
            href = dataHref;

        if (width && height && href && name && status && toolbar) {
            window.open(href, name, 'height=' + height + ',width=' + width + ',status=' + status + ',toolbar=' + toolbar, false);
            return false;
        }
    });
};

/*
initialiseFonts = function() {
    try {
        Cufon.replace('.font, .contentTitle');
    } 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);
    }
}

initialiseDefaultButtons = function() {
    try {
        //trace('initialiseDefaultButtons');

        var FORM_ID = '#' + $('form').attr('id');
        var DEFAULT_BUTTON_ATTRIBUTE = 'default';

        var KEY_EVENT_TO_TRACK = 'keydown';
        var MOUSE_EVENT_TO_TRIGGER = 'click';
        var SUBMIT_KEY_CODE = 13;

        $("input[" + DEFAULT_BUTTON_ATTRIBUTE + "]").each(function(i) {
            //trace(this);
            $(this).live(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
                                    if ($('form').valid()) {
                                        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);
    }
}


function registerNextTabControl(sSourceID, sTargetID) {
    $('#' + sSourceID).keydown(function(e) {
        if (e.which == 9) {
            e.preventDefault();
            $('#' + sTargetID).focus();
        }
    });

}

$(document).ready(function() {

    // PopupWindow :: http://plugins.jquery.com/project/PopupWindow
    var profiles = {
        popupToolsPrint: { height: 500, width: 600, center: 1, scrollbars: 1, status: 0, resizable: 1 },
        popupToolsEmail: { height: 400, width: 500, center: 1, scrollbars: 1, status: 0, resizable: 1 }
    };
    $(".tool").popupwindow(profiles);
    // jQuery Lightbox :: http://leandrovieira.com/projects/jquery/lightbox


});

/**********************************
* Custom scripts
**********************************/

/***** Popup windows *****/
function PopUpSend(URL) {
    window.open(URL, "Send", "height=400,width=500,scrollbars=yes,menubar=no,statusbar=no,personalbar=no,locationbar=no");
}
function PopUpPrint(URL) {
    window.open(URL, "Print", "height=500,width=500,scrollbars=yes,menubar=no,statusbar=no,personalbar=no,locationbar=no");
}


/***** Clear Input Text *****/
function clearText(thefield, clearType) {
    if (thefield.defaultValue == thefield.value) {
        thefield.value = ""
    }
}

scrollToTop = function() { $('html, body').animate({ scrollTop: 0 }, 'slow'); }

