if (typeof(console) == "undefined") {
    console = {
        log: function(){}
    };
};

function get_locale_code()
{
    return $('#current-lang a').attr('class') || "en";
}

function is_loogged_user() {
        return $('#member').is('.logged');
}

function get_service() {
    var service = "";

    //var parts = parseURL(document.location.toString());
    var parts = parseURL(document.location.href);
    var host_parts = parts.host.split(".");
    if (host_parts.length == 3 && host_parts[1] == "pho" && host_parts[2] == "to") {
        var services = ["avatar", "cartoon", "editor", "enhance", "funny", "makeup"];
        if ($.inArray(host_parts[0], services) != -1) {
            service = host_parts[0];
        }
    }

    return service;
}

function hitsInformerCounterIncrement(id)
{
    var url = 'http://hits.informer.com/log.php?id=' + id + '&r='+ Math.round(100000 * Math.random());
    new ImgLoader({url: url});
}

$(document).ready(function () {

    //Global
    isLogged = is_loogged_user();

    $("#del-account").click(function(e) {
        return confirm('Are your shure you want to delete your account?');
    });

    $(".signin-link").click(function(e){
        e.preventDefault();
        AuthManager.showSignIn();
    });
    $(".signup-link").click(function(e){
        e.preventDefault();
        AuthManager.showSignUp();
    });

    $("a.login-close").click(function () {
        $("#login").hide();
        return false;
    });

    current_lang = $('#current-lang a').attr('class')

    $('#current-lang').toggle(function() {
        $('#lang-dropdown ul').show();
    }, function () {
        $('#lang-dropdown ul').hide();
    })

    $('#lang-dropdown li a').click(function() {
        var lang = $(this).attr('class');
        if (current_lang != lang) {
            var url_info = parseURL(location.href);
            var host_parts = url_info.host.split(".");
            var pp = url_info.pathname.split("/");
            var ppl = pp.length;
            var is_index = (ppl==1  || pp[1] == "" || pp[1]=='index.php' || pp[1].length==2);
            //                .to        .to/           .to/index.php      .to/ru, .to/ru/..
            switch (host_parts[0]) {
                case "avatar":
                case "cartoon":
                case "editor":
                case "enhance":
                case "funny":
                case "makeup":
                case "tips":
                case "cards":
                case "digital":
                    if (lang=="en") {
                        location.href = "http://" + url_info.host + "/?lang=" + lang;
                    } else {
                        location.href = "http://" + url_info.host + "/" + lang;
                    }
                    return false;
                case "www":
                case "pho":
                    if (is_index) {
                        if (lang=="en") {
                            location.href = "http://" + url_info.host + "/?lang=" + lang;
                        } else {
                            location.href = "http://" + url_info.host + "/" + lang;
                        }
                        return false;
                    }
                }
                location.href = "http://" + url_info.host + url_info.pathname + "?lang=" + lang;
                return false;
                //location.href = location.href.replace(new RegExp('lang=[a-zA-Z]{2}'), 'lang=' + lang);
                //location.href = '/?lang=' + lang;
        } else {
            $('#current-lang').click();
        }
    })

    // pop-uping "Products" menu in the header
    $("#products-link").hover(
        function () {
            $(this).addClass("over");
            $("#products-menu").show();
        },
        function () {
            $(this).removeClass("over");
            $("#products-menu").hide();
        }
    );

    $("#services-link").hover(
        function () {
            $(this).addClass("over");
            $("#services-menu").show();
        },
        function () {
            $(this).removeClass("over");
            $("#services-menu").hide();
        }
    );

    $("#platforms-link").hover(
        function () {
            $(this).addClass("over");
            $("#platforms-menu").show();
        },
        function () {
            $(this).removeClass("over");
            $("#platforms-menu").hide();
        }
    );

    // Promt before delet albums on user pasge
    $("div.my-albums div.delete_ a").click(function() {
        var conf = confirm("Do you really want to delete this album?");
        if ( !conf )
            return false;
        var aid = $(this).attr("id").substr(2);
        $("#del-form input[name='id']").val(aid);
        $("#del-form").submit();
        return false;
    });

    $("div.my-images div.delete_ a").click(function() {
        var conf = confirm("Do you really want to delete this image?");
        if ( !conf )
            return false;
        var aid = $(this).attr("id").substr(2);
        $("#del-form input[name='id']").val(aid);
        $("#del-form").submit();
        return false;
    });
    // Auto-select-all by click the texareas on the album-info.php page
    $("#html-code, #ubb-code").bind("click", function() {
        $(this).select();
    });

    /*
    $("#footer").dblclick(function(){
        logger.show();
    });
    */
});

function update_img() {
    var img = document.getElementById('secure_img');
    var rnd = new Date();
    var rnd = Math.floor( Math.random()*10000 );
    img.src = 'http://pho.to/get_captcha.php?t=' + rnd;
    return false;
}


function update_captcha() {
    var img = document.getElementById('secure_img');
        var rnd = Math.floor( Math.random()*10000 );
    img.src = '/get_captcha.php?t=' + rnd;
    return false;
}

function preload_images(img_arr) {
    $.each(img_arr, function() {
        var img = new Image();
        img.src = "http://pho.to/img/" + this;
    });
}



function get_url_param (name) {
    var params = location.search.substring(1).split("&");
    var value = '';
    for (var i = 0; i < params.length; i++) {
        var split = params[i].split('=');
        if (split[0] == name){
            if (split.length > 1) value = split[1];
            return value;
        }
    }
    return null;
}

//PU1.0 :: parseURL by brothercake - http://www.brothercake.com/
//parse a URL to form an object of properties
function parseURL(url)
{
    //save the unmodified url to href property
    //so that the object we get back contains
    //all the same properties as the built-in location object
    var loc = { 'href' : url };

    //split the URL by single-slashes to get the component parts
    var parts = url.replace('//', '/').split('/');

    //store the protocol and host
    loc.protocol = parts[0];
    loc.host = parts[1];

    //extract any port number from the host
    //from which we derive the port and hostname
    parts[1] = parts[1].split(':');
    loc.hostname = parts[1][0];
    loc.port = parts[1].length > 1 ? parts[1][1] : '';

    //splice and join the remainder to get the pathname
    parts.splice(0, 2);
    loc.pathname = '/' + parts.join('/');

    //extract any hash and remove from the pathname
    loc.pathname = loc.pathname.split('#');
    loc.hash = loc.pathname.length > 1 ? '#' + loc.pathname[1] : '';
    loc.pathname = loc.pathname[0];

    //extract any search query and remove from the pathname
    loc.pathname = loc.pathname.split('?');
    loc.search = loc.pathname.length > 1 ? '?' + loc.pathname[1] : '';
    loc.pathname = loc.pathname[0];

    //return the final object
    return loc;
}

function implode (glue, pieces) {
    // Joins array elements placing glue string between items and return one string
    //
    // version: 911.718
    // discuss at: http://phpjs.org/functions/implode
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}


CRON = function (params) {
    this.interval = parseInt(params.interval) || 1000;
    this.id = 0;
    this.callback = params.callback;

    this.start = function () {
        var thisObj = this;
        this.stop();
        this.id = window.setInterval(function(){thisObj.action();}, this.interval);
    }

    this.action = function () {
        this.callback();
    }

    this.stop = function () {
        window.clearInterval(this.id);
    }
}


/*
 * Image Loader Class
 */
ImgLoader = function(params) {

    this._params = params;
    this._loaded = false;


    if (!params.url) {
        //l("Trying to load image with empty url.", "error");
        this._fire_callback('error', null);
        return;
        //throw new Error("ImgLoader error: no url provided");
    }

    //l("Start loading image: [" + params.url + "]", "info");
    var _i = new Image();
    var that = this;
    _i.onload = function() {
        that._onload(this);
    }
    _i.onerror = function() {
        that._onerror(this);
    }
    _i.src = params.url;

    if (_i.width || _i.height && !this._loaded) {
        // The image is in cache.
        this._loaded = true;
        this._fire_callback('cached', _i);
        this._fire_callback('load', _i);
        //l("Image loaded(from cache).", "info");
    }
}

ImgLoader.prototype = {
    _onload: function(i) {
        if (!this._loaded) {
            this._loaded = true;
            this._fire_callback('load', i);
            this._fire_callback('not_cached', i);
            //l("Image loaded.", "info");
        }
        i.onload = i.onerror = null;
    },

    _onerror: function(i) {
        this._loaded = true;
        this._fire_callback('error', i);
        i.onload = i.onerror = null;
        //l("Image couldn't be loaded.", "error");
    },

    _fire_callback: function (callback, context) {
        if (this._params[callback]) {
            this._params[callback].call(context);
        }
    }
}

String.prototype.supplant = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

/**********************************************************************/


/* Extend function. */

function extend(subClass, superClass) {
  var F = function() {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;

  subClass.superclass = superClass.prototype;
  if(superClass.prototype.constructor == Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  }
}



