/* 
 * common.js
 */
function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

var IELoader = {
    items: new Array(),
    orgdata : null,
    doneStatus: 0,
    doneNow: 0,
    ieLoadFixTime: 2000,
    ieTimeout: "",
    init: function(images, orgdata) {
        $(document).ready(function() {
            IELoader.items = images;
            IELoader.orgdata = orgdata;
            //help IE drown if it is trying to die :)
            IELoader.ieTimeout = setTimeout("IELoader.ieLoadFix()", IELoader.ieLoadFixTime);
            IELoader.loader();
	});
    },
      
    loader: function() {
        var length = IELoader.items.length; 
        IELoader.doneStatus = length;
		
        for (var i = 0; i < length; i++) {
            var imgLoad = $("<img></img>");
            $(imgLoad).attr("src", IELoader.items[i]);
            $(imgLoad).unbind("load");
            $(imgLoad).bind("load", function() {
                if ( typeof IELoader.orgdata[i-1] != 'undefined' ) {
                    $("#box_" + IELoader.orgdata[i-1].file_id + " .loader").hide();
                    $("#box_" + IELoader.orgdata[i-1].file_id + " .thumb").show();
                }
                
                IELoader.imgCallback();
            });
        }
    },
      
    ieLoadFix: function() {
        while ((100 / IELoader.doneStatus) * IELoader.doneNow < 100) {
            IELoader.imgCallback();
        }
    },
	
    imgCallback: function() {
        IELoader.doneNow ++;
        if ( IELoader.doneNow >= IELoader.doneStatus ) {
            IELoader.doneLoad();
        }
    },
	
    doneLoad: function() {
        //prevent IE from calling the fix
        clearTimeout(IELoader.ieTimeout);
        $(".loader").hide();
        $(".thumb").show();
    }
};

(function($) {
    $.preLoadImages = function(imageList,orgdata, callback) {
        var pic = [], i, total, loaded = 0;
        if (typeof imageList != 'undefined') {
            if ($.isArray(imageList)) {
                total = imageList.length; // used later
                for (i=0; i < total; i++) {
                    pic[i] = new Image();
                    pic[i].onload = function() {
                        loaded++; // should never hit a race condition due to JS's non-threaded nature
                        if ( typeof orgdata[loaded-1] != 'undefined' ) {
                            $("#box_" + orgdata[loaded-1].file_id + " .loader").hide();
                            $("#box_" + orgdata[loaded-1].file_id + " .thumb").show();
                        }
                        if (loaded == total) {
                            if ($.isFunction(callback)) {
                                callback();
                            }
                        }
                    };
                    pic[i].src = imageList[i];
                }
            }
        }
        pic = undefined;
    };
})(jQuery);

// preloader
(function($) {
    var imgList = [];
    $.extend({
        preload: function(imgArr, option) {
            var setting = $.extend({
                init: function(loaded, total) {},
                loaded: function(img, loaded, total) {},
                loaded_all: function(loaded, total) {}
            }, option);
            var total = imgArr.length;
            var loaded = 0;
            setting.init(0, total);
            for(var i in imgArr) {
                imgList.push($("<img />")
                    .attr("src", imgArr[i])
                    .load(function() {
                        loaded++;
                        setting.loaded(this, loaded, total);
                        if(loaded == total) {
                            setting.loaded_all(loaded, total);
                        }
                    })
                );
            }
        }
    });
})(jQuery);

function setErrorBar ( msg, el, stopfadeout ) {
    // make sure all bars are hidden
    hideInfoBars();

    if ( el ) {
        element = '#' + el;
    } else {
        element = '#errorbar';
    }
    // remove hidden class
    $(element).removeClass ( 'forcehidden' );
    $(element + " p").html ( msg );
    $(element).fadeIn();

    $("body").scrollTo( $(element), { duration:500 });
    if ( !stopfadeout ) {
        setTimeout(resetInfoBars, 5000);
    }
}

function setAlertBar ( msg ) {
    // make sure error bar is hidden
    hideInfoBars();
    $("#alertbar").removeClass ( 'hidden' );
    $("#alertbar p").html ( msg );
    $("#alertbar").fadeIn();
    $("body").scrollTo( $("#alertbar"), { duration:500 });
}
function setInfoBar ( msg ) {
    // make sure error bar is hidden
    hideInfoBars();
    $("#infobar").removeClass ( 'forcehidden' );
    $("#infobar p").html ( msg );
    $("#infobar").fadeIn();
    $("body").scrollTo( $("#infobar"), { duration:500 });
    setTimeout(resetInfoBars, 5000);
}
function resetInfoBars () {
    $(".toolTip").fadeOut();
}

function hideErrorBars () {
    $("#errorbar").hide();
}

function hideInfoBars () {
    $(".toolTip").hide();
}

function defined ( varname ) {
    return ( typeof varname !== 'undefined' ) ? true : false;
}
function in_array (needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false

    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}


$(function(){
    $.fn.wait = function(time, type) {
        time = time || 3000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };

    //-- Hide tooltip on close
    $('.toolTip .close').live('click', function(){
        $(this.parentNode).fadeOut(function(){
            $(this).remove();
        });
    });

    $('.error .close').click(function(){
        $(this.parentNode).fadeOut(function(){
            $(this).remove();
        });
    });
});
