
// change default shortcut to jQuery from "$" to "jQuery"
// ref. http://docs.jquery.com/Using_jQuery_with_Other_Libraries
jQuery.noConflict();

// override jQuery.fn.bind to wrap every provided function in try/catch
var jQueryBind = jQuery.fn.bind;
jQuery.fn.bind = function(type, data, fn) {
    if (! fn && data && typeof data == 'function') {
        fn = data;
        data = null;
    }
    if (fn) {
        var origFn = fn;
        var wrappedFn = function() {
            try  {
                //origFn.apply(this, arguments);
                return origFn.apply(this, arguments);
            } catch (ex) {
                track_error(ex);
                // re-throw ex iff error should propogate
                // throw ex;
            }
        };
        fn = wrappedFn;
    }
    return jQueryBind.call(this, type, data, fn);
};


var windowsisunloading = false;
window.onbeforeunload = function () {
   windowsisunloading = true;
};

// Error tracking function
// err: a string or an Error object
function track_error(err) {

    if (windowsisunloading) {
        return true;
    }

    var msg = 'Unknown error';
    if (err.message) {
        msg = err.message;
    } else if (typeof err == 'string' || typeof err == 'String') {
        msg = err;
    }

    title = 'JS error';
    browser = '';
    jQuery.each(jQuery.browser, function(i, val) {
        if (i == 'version') {
            browser = browser + 'version="' + val + '" ';
        } else if (val == true) {
            browser = browser + 'browser="' + i + '" ';
        }
    });
    // html code is truncated to not reach max allowed post limit
    fullhtml = document.getElementsByTagName('html')[0].innerHTML;
    if (fullhtml.length > 4096) {
        fullhtml = fullhtml.substring(0, 4096) + '[...]';
    }

    jQuery.post('/w/common/debug_js.php', {title: title, msg: msg, browser: browser, fullhtml: fullhtml});

};

// Attach track_error to window's onerror event;
// use onerror instead of $(window).error( ... ) in order to get url and lineNo
window.onerror = function(msg, url, lineNo) {
    track_error([ msg, url, lineNo ].join('; '));
    // return true to stop error from propogating, false to allow propogation
    //return true;
    return false;
};

// handle ajax errors
// TODO: this may cause loop on jQuery.post [...] debug_js.php [...] error
/*
jQuery(document).ajaxError(function(request, settings){
    track_error('status: ' + settings.status + ' (' + settings.statusText + '), response: "' + settings.responseText + '"');
});
*/

//    if (window.console && window.console.error) {
//        console.error(arguments);
//    }

jQuery(document).ready(function() {

  try {
  
        // main toggle function
        jQuery.fn.fadeToggle = function(speed, easing, callback) {
             return this.animate({opacity: 'toggle'}, speed, easing, callback);
        };

        // main replace function
        fadeReplace = function(div1, div2) {
            if (div1.is(':visible')) {
                return div1.fadeOut('fast', function() {
                    div2.fadeIn('fast');
                });
            } else {
                return div2.fadeOut('fast', function() {
                    div1.fadeIn('fast');
                });
            }
        };

        // proper disable link
        jQuery('.no_link').click(
            function() {
                return false;
            }
        );

        // is_search
        jQuery('a.is_search').click(
            function() {
                location = jQuery(this).attr('href') + '?is_search=1';
                return false;
            }
        );


        // override home page links to disable LF_LOC cookie redirection
        jQuery('a.home').click(
            function() {
                location = jQuery(this).attr('href') + '?nr=1';
                return false;
            }
        );

        // facebox
        _facebox = 'a[rel*=facebox]';
        if (jQuery(_facebox).length > 0) {
            jQuery(_facebox).facebox();
        }

        // proper disable right click
        jQuery('img.no_right_click').each(function() {
            jQuery(this).attr('oncontextmenu', 'return false;');
        });

        // wrap "a href class but" with a span
        jQuery('a.but').each(function() {
            var html = '<span>' + jQuery(this).html() + '</span>';
            jQuery(this).html(html);
        });

        jQuery('a.but2').each(function() {
            var html = '<span>' + jQuery(this).html() + '</span>';
            jQuery(this).html(html);
        });

        // proper taget _blank
        //$('a[@rel$="external"]').click(function() {
        jQuery('a[rel*=external]').click(function() {
            this.target = '_blank';
        });


        // carrousel
        if (jQuery('ul.pages > li').length > 1) {

            jQuery('.gallery').slideShow({
                slideEl:'div.gallery-wrap div.sub-gallery-box',
                linkNext:null,
                linkPrev:null,
                linkPause:null,
                numElementLink:'ul.pages li a',
                duration:1200,
                autoSlideShow:true,
                switchTime:3500,
                event:'click',
                currentEl:'#footer span.cur',
                allEl:'#footer span.all'
            });

        }
        // end carrousel

        // slidebox
        var _parentSlide = 'div.slide-block';
        var _linkSlide = 'div.title';
        var _slideBlock = 'div.block';
        var _openClassS = 'active';
        var _durationSlide = 500;

        jQuery(_parentSlide).each(function(){
            if (! jQuery(this).is('.'+_openClassS)) {
                jQuery(this).find(_slideBlock).css('display','none');
            }
        });

        jQuery(_linkSlide,_parentSlide).click(function(){
            if (jQuery(this).parents(_parentSlide).is('.'+_openClassS)) {
                jQuery(this).parents(_parentSlide).removeClass(_openClassS);
                jQuery(this).parents(_parentSlide).find(_slideBlock).slideUp(_durationSlide);
            } else {
                jQuery(this).parents(_parentSlide).addClass(_openClassS);
                jQuery(this).parents(_parentSlide).find(_slideBlock).slideDown(_durationSlide);
            }
            return false;
        });
        // end slidebox

        // jcarousel
        var _mycarousel = '#mycarousel';
        var _mycarouselitem = 'li.mycarouselitem';
        
        // precache next images to display
        function mycarousel_loadNextPage(current_item) {
            try {
                jQuery('img.delayed').each(function() {
                    var self = jQuery(this);
                    if (self.parent().parent().parent().attr('jcarouselindex') <= 7 + current_item) {
                        self.attr('src', jQuery(self).attr('title'));
                        self.removeAttr('title');
                        self.removeClass('delayed');
                    }
                    
                });
             } catch (ex) {
                track_error(ex);
            }
        }
        
        function mycarousel_initCallback(carousel) {
            // Disable autoscrolling if the user clicks the prev or next button.
            jQuery('#my-jcarousel-prev').bind('click', function() {
                carousel.startAuto(0);
                carousel.prev();
                return false;
            });

            jQuery('#my-jcarousel-next').bind('click', function() {
                carousel.startAuto(0);
                carousel.next();
                return false;
            });

            jQuery('.jcarousel-control a').bind('click', function() {
                carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
                // Disable autoscrolling if the user clicks the prev or next button.
                carousel.startAuto(0);
                return false;
            });

            // Pause autoscrolling if the user moves with the cursor over the clip.
            carousel.clip.hover(function() {
                carousel.stopAuto();
            }, function() {
                carousel.startAuto();
            });

            // Pause autoscrolling if the user moves with the cursor over the clip.
            jQuery('#my-jcarousel-prev, #my-jcarousel-next').hover(function() {
                carousel.stopAuto();
            }, function() {
                carousel.startAuto();
            });

            // Pause autoscrolling if the user moves with the cursor over the clip.
            jQuery('.jcarousel-control a').hover(function() {
                carousel.stopAuto();
            }, function() {
                carousel.startAuto();
            });
        };

        function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
            jQuery('.jcarousel-control li').removeClass("active");
            jQuery('#bubble'+ idx).addClass("active");
            
            mycarousel_loadNextPage(idx);
            
            var page_id = Math.floor(jQuery('#bubble'+ idx).position().left / 196);
            var first_in_page = 1 + page_id * 7;
            var last_in_page = 7 + page_id * 7;
            if (last_in_page > jQuery(_mycarouselitem).length) {
                last_in_page = jQuery(_mycarouselitem).length;
            }

            jQuery('div.bubblecont ul').animate({marginLeft:'-' + 196 * page_id + 'px'}, 'slow');
            jQuery('#pagelabel').html(page_label_default.replace('##FIP##', first_in_page).replace('##LIP##', last_in_page));
        };

        if (jQuery(_mycarousel).length > 0) {
            jQuery('#sidebar2 .gallery-wrap').css('visibility', 'visible');
            if (jQuery(_mycarouselitem).length > 1) {

                if (typeof(page_label_default) == 'undefined') {
                    var page_label_default = jQuery('#pagelabel').html();
                }
				
                jQuery(_mycarousel).jcarousel({
                    scroll: 1,
                    auto: 2,
                    animation: 'slow',
                    initCallback: mycarousel_initCallback,
                    itemFirstInCallback:  mycarousel_itemFirstInCallback
                });
            }
            mycarousel_loadNextPage(1);
        }
    } catch (ex) {
        track_error(ex);
        // re-throw ex iff error should propogate
        // throw ex;
    }

});

function run_ajax(container, url, options) {
    // this function use prototype
    $(container).innerHTML = '<img src="/p/wait.gif" width="25" height="23" alt="">';

    this.container = container;
    var onComplete = options.onComplete || Prototype.emptyFunction;
    options.onComplete = (function() {
            onComplete();
        }).bind(this);

    options.onFailure = function(t) {
        alert(msg_ajax_error_failure + t.status + ' - ' + t.statusText + ').');
    };
    options.on403 = function(t) {
        alert(msg_ajax_error_403);
    };
    options.on404 = function(t) {
        alert(msg_ajax_error_404);
    };
    var day_date = new Date();
    t = Date.parse(day_date);
    options['parameters']+= '&timestamp=' + t;
    var my_ajax = new Ajax.Updater(container, url, options);
};

replace_char = function(str, findstring, newstring) {
    i           = 0;
    k           = 0;
    clean_str   = '';
    char_find   = false;
    while (i < str.length) {
        c = str.charAt(i);
        if (c == findstring.charAt(k)) {
            char_find = true;
            k++;
        } else {
            if (char_find == true) {
                for(z = i-k; z < i; z++) {
                    clean_str = clean_str + str.charAt(z);
                }
            }
            char_find = false;
            k = 0;
        };
        if (char_find == false) {
            clean_str = clean_str+c;
            i++;
         } else {
            if (k == findstring.length) {
                clean_str = clean_str + newstring;
                char_find = false;
                k = 0;
            }
            i++;
        }
    }
    return clean_str;
};

function ajax_code(str) {
    str = replace_char(str, '&', '¤¤1¤¤');
    str = replace_char(str, '?', '¤¤2¤¤');
    str = replace_char(str, '+', '¤¤3¤¤');
    str = replace_char(str, '€', '¤¤4¤¤');
    str = replace_char(str, '’', '¤¤5¤¤');
    str = replace_char(str, '…', '¤¤6¤¤');
    str = replace_char(str, 'œ', '¤¤7¤¤');
    str = replace_char(str, '%', '¤¤8¤¤');
    return str;
};

raise_msg_popup = function(title, msg) {
    var popup = '';
    popup+= '<div id="raise_msg_popup" class="popup">';
    popup+= '   <div class="popup-content">';
    popup+= '       <img src="/p-3.3.0/default/icon4.gif" alt="info" />';
    popup+= '       <strong style="font-size:16px;">' + title + '</strong>';
    popup+= '           <p>' + msg + '</p>';
    popup+= '   </div>';
    popup+= '   <div class="popup-bottom">&nbsp;</div>';
    popup+= '</div>';

    jQuery.facebox(popup);
};
