/*********************************************************************
* Copyright 2011 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();
    initialiseAddClass();
    initialiseTriggers();
    initialiseScrollables();
    initialiseAddClass();
    initialiseFlash();
    intialiseToggle();
    checkForException();

});



scrollText = function(event, element) {
    if (event === null) return;

    var $this = /li/i.test(event.target.nodeName) ? $(element).children('div') : $(element);
    var $span = $this.children('span');
    var spanHeight = $span.height();


    if (event.type == 'mouseenter' && spanHeight > 55) $span.stop().animate({ top: ($this.height() - ($this.height() * 2)) }, 1000);
    else {
        $span.stop().animate({ top: "1px" });
    }
};


$(function() {
    $('.Scrolltext').bind('mouseenter', function(event) {
        scrollText(event, this);
    }).bind('mouseleave', function(event) {
        scrollText(event, this);
    }).parent().bind('mouseenter', function(event) {
        scrollText(event, this);
    }).bind('mouseleave', function(event) {
        scrollText(event, this);
    });
});

intialiseToggle = function() {
    var toggleAction = '.toggle-action',
        toggleTarget = '.toggle-target',
    //show first item
        showElement = $(toggleTarget)[0],
        speed = '800',
        hideSiblings = false;

    $(toggleTarget).hide();
    $(showElement).show();

    $(toggleAction).each(function(e) {
        $(this).bind('click', function() {
            var $$ = $(this);
            var nextTarget = $$.next(toggleTarget);
            nextTarget.slideToggle(speed);
            $$.addClass('select').siblings(toggleAction).removeClass('select');
            if (hideSiblings !== true) {
                $(nextTarget).siblings("div:visible").slideUp(speed)
            }
            return false;
        });
    });

};


// CUSTOM RogenSi Add extra class on Main menu item */
initialiseAddClass = function() {
    var navItems = $("#nav-main ul li").nextAll();
    var nav = $(navItems).not("#nav-main ul li ul li");

    $(nav).each(function() {
        if (nav.length > 0) {
            for (var i = 0; i < nav.length; i++)
                $(nav[i]).addClass("list" + (i + 1));
        }

    });

};



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;
};

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);
    }
};

// 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);
    }
};


initialiseOverlays = function() {
    try {
        trace('initialiseOverlays');

        // iframe overlays
        trace($('a[rel^=#iframe-overlay]'));
        $('a[rel^=#iframe-overlay]').overlay({
            mask: '#000000',
            onBeforeLoad: function() {
                var $overlay = this.getOverlay(); trace($overlay);
                var iframe = ($overlay.find('iframe').length > 0 ? $overlay.find('iframe')[0] : undefined);
                if (typeof iframe != 'undefined') {
                    var $trigger = this.getTrigger();
                    trace($trigger.attr('href'));
                    iframe.src = $trigger.attr('href');
                }
            },
            onClose: function() {
                var $overlay = this.getOverlay(); trace($overlay);
                var iframe = ($overlay.find('iframe').length > 0 ? $overlay.find('iframe')[0] : undefined);
                iframe.src = ''; // clear the iframe while waiting for the new page to load
            }
        });
    } catch (e) {
        trace(e);
    }
};

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: 'fade',
                    fadeInSpeed: 300,
                    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 CAUSES_VALIDATION_CLASS = 'causesValidation';

        var KEY_EVENT_TO_TRACK = 'keydown';
        var MOUSE_EVENT_TO_TRIGGER = 'click';
        var SUBMIT_KEY_CODE = 13;
        
        // TODO: use delegate with jQuery 1.4.5+
        $("input[" + DEFAULT_BUTTON_ATTRIBUTE + "]").each(function(i) {
            $(this).bind(KEY_EVENT_TO_TRACK, function(event) {
                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;
                                var causes_validation = $(default_button_id).hasClass(CAUSES_VALIDATION_CLASS);

                                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
                                    //console.log(causes_validation);

                                    if (causes_validation) {
                                        returnCode = $('form').valid() && $(default_button_id).trigger(MOUSE_EVENT_TO_TRIGGER);
                                    } else {
                                        $(default_button_id).click();
                                        return true;
                                    }
                                } 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);
    }
}

var $$ = (function(window, undefined) {
    var $_ID_PREFIX       = '#';
    var $_CLASS_PREFIX    = '.';
    var $_ATTR_WRAPPERS   = { 
        start       : '[', 
        end         : ']', 
        assignment  : '=' 
    };

    var _$$ = window.$$ || {};
    _$$['id'] = function(id, tag) {
        if (tag === undefined)
            return $_ID_PREFIX + id;
            
        return tag + $_ID_PREFIX + id;
    };
    _$$['cssClass'] = function(cssClass, tag) {
        if (tag === undefined) 
            return $_CLASS_PREFIX + cssClass;
        
        return tag + $_CLASS_PREFIX + cssClass;
    };
    _$$['attr'] = function(attr, value, tag) {
        if (value === undefined)
            return $_ATTR_WRAPPERS.start + attr + $_ATTR_WRAPPERS.end;
        
        if (tag === undefined)
            return $_ATTR_WRAPPERS.start + attr + $_ATTR_WRAPPERS.assignment + value + $_ATTR_WRAPPERS.end;
        
        return tag + $_ATTR_WRAPPERS.start + attr + $_ATTR_WRAPPERS.assignment + value + $_ATTR_WRAPPERS.end;
    };
    
    // if jQuery if found, we extend $$ by including jQuery methods
    if (window.jQuery !== undefined) {
        var $ = window.jQuery;
        
        _$$['$id'] = function(id, tag) {
            return $(_$$.id(id, tag));
        };
        _$$['$cssClass'] = function(cssClass, tag) {
            return $(_$$.cssClass(cssClass, tag));
        };
        _$$['$attr'] = function(attr, value, tag) {
            return $(_$$.attr(attr, value, tag));
        };
    }
    
    return _$$;
}) (window, undefined);

var createLabel = function($element, value) {
    $element.val(value);
}

$(function() {
    var INITIAL_VALUE_ATTR = 'data-initial-value';
    $($$.attr(INITIAL_VALUE_ATTR)).each(function(i) {
        // initial setup
        var $this = $(this);
        var value = $this.attr(INITIAL_VALUE_ATTR);
        if (value && !$this.val()) createLabel($this, value);

        $('body')
        .delegate($$.attr(INITIAL_VALUE_ATTR), 'click', function(e) { // initial click
            var $this = $(this);
            var value = $this.attr(INITIAL_VALUE_ATTR);

            if ($this.val() == value) {
                createLabel($this, '');
            }
        })
        .delegate($$.attr(INITIAL_VALUE_ATTR), 'blur', function(e) { // on blur
            var $this = $(this);
            var value = $this.attr(INITIAL_VALUE_ATTR);

            if ($this.val() == '') {
                createLabel($this, value);
            }
        });
    });
});

