/// <reference path="jquery-1.3.2-vsdoc.js" />

//jQuery(document).ready(function() {
//    placeSize("#main_wrapper");
//    placeObject("#side", "#main_wrapper");
//    jQuery(window).resize(function() {
//        placeSize("#main_wrapper");
//        placeObject("#side", "#main_wrapper");
//    });
//});

/*function placeSize(object) {
    var max = $(document).width();
    var newSize = 780;
    if (max > 1200) {
        newSize = 980;
    }
    jQuery(object).css({ 'width': newSize + 'px' });
    if (newSize == 780) {
        jQuery(object).css({ 'margin': '0px 0px 0px 5px' });
    } else {
        jQuery(object).css({ 'margin': '0 auto' });
    }
    //document.getElementById('dw').innerHTML = max;
    //document.getElementById('mw').innerHTML = newSize;
}

function placeObject(object, relative) {
    var rel = jQuery(relative);
    var relOffset = jQuery(rel).offset();
    var relWidth = jQuery(rel).width();
    var offsetLeft = relOffset.left + relWidth + 1;
    jQuery(object).css({ 'left': offsetLeft + 'px' });
}*/

$(window).load(function() {
    //$(document).ready(function() {
    //$('a[rel="external"]').click(function() {
    //    window.open($(this).attr('href'));
    //    return false;
    //});

    //$(document).ready(function() {
    $('a[rel="external"]').attr('target', '_blank');
    //});

    $('a[target="helgonmain"]').each(function() {
        $(this).removeAttr('target');
    });

    //$(".tt").ellipsis();

    $('.fp').tipTip({ maxWidth: 'auto', extraStart: '<img src="', extraEnd: '.jpg" class="img0">' });

    if ($("#sonline").length) {
        StatusCheck();
    }

    if ($("#lockside").length) {
        lockside_init();
    }
});

window.onscroll = function() {
    if ($("#lockside").length) {
        lockside();
    }
}

var iSideDiff;

function lockside_init() {
    var iSide1, iSide2;
    if ($("#lockheader").length) { //sticky top
        iSide1 = $('#lockside').offset().top + $('#lockside').height();
        iSide2 = (window.innerHeight ? window.innerHeight : $(window).height()) - $('#footer').height();
    } else {
        iSide1 = $('#lockside').height();
        iSide2 = (window.innerHeight ? window.innerHeight : $(window).height()) - $('#footer').height();
    }

    iSideDiff = iSide2 - iSide1;

    lockside();
}

function lockside() {
    if (iSideDiff > 0) { //lock
        if ($("#lockheader").length) { //sticky top
            $('#lockside').css('position', 'fixed');
            $('#lockside').css('top', '142px');
            $('#lockside').css('width', '234px');
        } else {
            if (getScrollHeight() > 142) {
                $('#lockside').css('position', 'fixed');
                $('#lockside').css('top', '0px');
            } else {
                $('#lockside').css('position', 'absolute');
                $('#lockside').css('top', 'auto');
            }

            $('#lockside').css('width', '234px');
        }
        
        var iMax1 = $('#content').height();
        var iMax2 = $('#lockside').height();
        if (iMax1 > iMax2) {
            $('#main').css('min-height', iMax1);
        } else {
            $('#main').css('min-height', iMax2);
        }
    }
}

function getScrollHeight() {
    var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;

    return h ? h : 0;
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null) {
        return "";
    } else {
        return results[1];
    }
}

function validate(string2, caption, lengthmin, lengthmax) {
    if (trim(string2).length < lengthmin) {
        alert('Fältet "' + caption + '" måste innehålla minst ' + lengthmin + ' tecken.');
        return false;
    }
    if (trim(string2).length > lengthmax) {
        alert('Fältet "' + caption + '" får max innehålla ' + lengthmax + ' tecken.');
        return false;
    }
    return true;
}
function FC(sField, iMax) {
    //var iC = $("#" + sField).val().length;
    //$('span#' + sField + '_c').html(iC);
    var iC = parseInt(document.getElementById(sField).value.length);
    var iLeft = iMax - iC;
    document.getElementById(sField + '_c').innerHTML = iLeft;
}

function pagescroller(iTop) {
    if ($("#lockheader").length) {
        $('html, body').animate({ scrollTop: iTop - 130 }, 0);
    } else {
        $('html, body').animate({ scrollTop: iTop }, 0);
    }
}

(function($) {
    //$("#myTextArea").charCounter(max, container, settings);
    $.fn.charCounter = function(max, container, settings) {
        max = max || 100;
        settings = $.extend({
            //container: "counter",
            pulse: true,
            delay: 1
        }, settings);
        var p, timeout;

        function count(el, container) {
            el = $(el);
            if (el.val().length > max) {
                el.val(el.val().substring(0, max));
                if (settings.pulse && !p) {
                    pulse(container, true);
                };
            };
            if (settings.delay > 0) {
                if (timeout) {
                    window.clearTimeout(timeout);
                }
                timeout = window.setTimeout(function() {
                    container.html((max - el.val().length));
                }, settings.delay);
            } else {
                container.html((max - el.val().length));
            }
        };

        function pulse(el, again) {
            if (p) {
                window.clearTimeout(p);
                p = null;
            };
            el.animate({ opacity: 0.1 }, 100, function() {
                $(this).animate({ opacity: 1.0 }, 100);
            });
            if (again) {
                p = window.setTimeout(function() { pulse(el) }, 200);
            };
        };

        return this.each(function() {
            /*var container = (!settings.container.match(/^<.+>$/))
				? $(settings.container)
				: $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);*/
            $(this)
				.bind("keydown", function() { count(this, container); })
				.bind("keypress", function() { count(this, container); })
				.bind("keyup", function() { count(this, container); })
				.bind("focus", function() { count(this, container); })
				.bind("mouseover", function() { count(this, container); })
				.bind("mouseout", function() { count(this, container); })
				.bind("paste", function() {
				    var me = this;
				    setTimeout(function() { count(me, container); }, 10);
				});
            if (this.addEventListener) {
                this.addEventListener('input', function() { count(this, container); }, false);
            };
            count(this, container);
        });
    };

})(jQuery);


function del(href, sQ) {
    if (confirm(sQ)) {
        location.href = href;
    }
}
function ks(form, e) {
    if (e.ctrlKey && 13 == e.keyCode) {
        vd(form);
    }
}
function pop(file, name, options) {
    var w = window.open(file, name, options);
    if (window.focus) {
        w.focus();
    }
    return false;
}
function ca(formname, checkname, thestate) {
    var c;
    var el_collection = eval("document.forms." + formname + "." + checkname);

    for (c = 0; c < el_collection.length; c++) {
        el_collection[c].checked = thestate;
    }
}
function cc(sField) {
    var c;
    var el_collection = eval(sField);
    var iChecked = 0;

    for (c = 0; c < el_collection.length; c++) {
        if (el_collection[c].checked == true) {
            iChecked += 1;
        }
    }

    return iChecked;
}
function trim(sTxt) {
    return sTxt.replace( /(^\s+)|(\s+$)/g, "");
}
function pa(t, i, u) {
    if (confirm('Är du säker på att du vill rapportera detta inlägg till Helgon crew?')) {
        newwindow = window.open('/abuse/default.aspx?t=' + t + '&i=' + i + '&u=' + u, 'popab', 'height=300,width=500');
        if (window.focus) { newwindow.focus() }
        return false;
    }
}
function pag(t, i, u) {
    if (confirm('Är du helt säker på att du vill rapportera den här bilden till crew?')) {
        newwindow = window.open('/abuse/default.aspx?t=' + t + '&i=' + i + '&u=' + u, 'popab', 'height=300,width=500');
        if (window.focus) { newwindow.focus() }
        return false;
    }
}

function ET(param1, param2, flag) {
    if (flag == true) {
        document.getElementById(param1).style.display = 'none';
        if (param2 != '') {
            document.getElementById(param2).style.display = 'block';
        }
    }
    else {
        document.getElementById(param1).style.display = 'block';
        if (param2 != '') {
            document.getElementById(param2).style.display = 'none';
        }
    }
}

function FocusLast(sField) {
    setCursor(sField, sField.value.length);
}
//TODO:Rewrite
function daysElapsed(whenYear, whenMonth, whenDay, reverse) {
    var currentTime = new Date();
    var start = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate());
    var end = new Date(whenYear, whenMonth - 1, whenDay);
    var difference;

    if (reverse == '') {
        difference = start - end;
    } else {
        difference = end - start;
    }

    var daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);

    return daysDifference;
}

function setCursor(el, pos) {
    if (el.setSelectionRange) {
        el.focus();
        el.setSelectionRange(pos, pos);
    }
    else {
        if (el.createTextRange) {
            range = el.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
}

function lt(l) {
    $.post('../do/do.aspx?do=l&l=' + l, function() {
        location.href = location.href;
        //location.reload();
    });
}

/*(function($) {
    $.fn.ellipsis = function(enableUpdating) {
        var s = document.documentElement.style;
        if (!('textOverflow' in s || 'OTextOverflow' in s)) {
            return this.each(function() {
                var el = $(this);
                if (el.css("overflow") == "hidden") {
                    var originalText = el.html();
                    var w = el.width();

                    var t = $(this.cloneNode(true)).hide().css({
                        'position': 'absolute',
                        'width': 'auto',
                        'overflow': 'visible',
                        'max-width': 'inherit'
                    });
                    el.after(t);

                    var text = originalText;
                    while (text.length > 0 && t.width() > el.width()) {
                        text = text.substr(0, text.length - 1);
                        t.html(text + "...");
                    }
                    el.html(t.html());

                    t.remove();

                    if (enableUpdating == true) {
                        var oldW = el.width();
                        setInterval(function() {
                            if (el.width() != oldW) {
                                oldW = el.width();
                                el.html(originalText);
                                el.ellipsis();
                            }
                        }, 200);
                    }
                }
            });
        } else return this;
    };
})(jQuery);*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var tStatus;
var iGuestBook = 0;
var iMail = 0;
var iDiary = 0;
var iGallery = 0;
var iForum = 0;
var iFriends = 0;
var iIcon = 0;

function ChangeImg(iOldValue, iValue, sWhat, sTitle) {
    $link = $("#" + sWhat + "i");
    if (!(iOldValue == iValue)) {
        if (iValue > 0) {
            if (iIcon == 0) {
                $link.attr("src", "/_static/i/ico/" + sWhat + "1b.gif");
                $link.attr("alt", sTitle);
                $link.attr("title", sTitle);
            } else {
                $link.attr("src", "/_static/i/ico/" + sWhat + "1.gif");
                $link.attr("alt", sTitle);
                $link.attr("title", sTitle);
            }
        } else {
            $link.attr("src", "/_static/i/ico/" + sWhat + ".gif");
            $link.attr("alt", sTitle);
            $link.attr("title", sTitle);
        }
    }
    return iValue;
}

function GetFriends() {
    //$('#quickf').append('<option value="1">test 1</option><option value="3">test 3</option><option value="3">test 3</option>');
    $.get("/xml/f.aspx", {}, function(xml) {
        $('friends', xml).each(function(i) {
            $('#quickf').append('<option value="1">' + + '</option>');
        });
    });
}

function StatusCheck() {
    $.ajax({
        type: "GET",
        async: true,
        cache: false,
        url: "/xml/s.aspx",
        dataType: "xml",
        success: function (xml) {
            $("#sonline").text($(xml).find("s").text());
            iIcon = $(xml).find("i").text();
            iGuestBook = ChangeImg(iGuestBook, $(xml).find("gu").text(), "gu", $(xml).find("gus").text());
            iMail = ChangeImg(iMail, $(xml).find("ma").text(), "ma", $(xml).find("mas").text());
            iDiary = ChangeImg(iDiary, $(xml).find("di").text(), "di", $(xml).find("dis").text());
            iGallery = ChangeImg(iGallery, $(xml).find("ga").text(), "ga", $(xml).find("gas").text());
            iForum = ChangeImg(iForum, $(xml).find("fo").text(), "fo", $(xml).find("fos").text());
            iFriends = ChangeImg(iFriends, $(xml).find("fr").text(), "fr", $(xml).find("frs").text());
        }
    });
    tStatus = setTimeout("StatusCheck()", 5000);
    /*$.get("/xml/s.aspx?r=" + Math.random(), {}, function(xml) {
        $('item', xml).each(function(i) {
            $("#sonline").text($(this).find("s").text());
            iGuestBook = ChangeImg(iGuestBook, $(this).find("gu").text(), "gu", $(this).find("gus").text());
            iMail = ChangeImg(iMail, $(this).find("ma").text(), "ma", $(this).find("mas").text());
            iDiary = ChangeImg(iDiary, $(this).find("di").text(), "di", $(this).find("dis").text());
            iGallery = ChangeImg(iGallery, $(this).find("ga").text(), "ga", $(this).find("gas").text());
            iForum = ChangeImg(iForum, $(this).find("fo").text(), "fo", $(this).find("fos").text());
            iFriends = ChangeImg(iFriends, $(this).find("fr").text(), "fr", $(this).find("frs").text());
        });
        tStatus = setTimeout("StatusCheck()", 5000);
    });*/
}

var tStatusTest;
function ChangeTxt(iValue, sWhat, sTitle) {
    $link = $("#ad_" + sWhat + "i");
    if (iValue > 0) {
        $link.attr("style", "color:white;");
        $link.attr("alt", sTitle);
        $link.attr("title", sTitle);
    } else {
        $link.attr("style", "");
        $link.attr("alt", sTitle);
        $link.attr("title", sTitle);
    }
}
function GetText(xml, sWhat) {
    ChangeTxt($(xml).find(sWhat).text(), sWhat, $(xml).find(sWhat + "s").text());
}
function StatusCheckTest() {
    $.ajax({
        type: "GET",
        async: true,
        cache: false,
        url: "/xml/a.aspx?r=",
        dataType: "xml",
        success: function(xml) {
            GetText(xml, "pv");
            GetText(xml, "no");
            GetText(xml, "ga");
            GetText(xml, "gn");
            GetText(xml, "rp");
            //GetText(xml, "ku");
            //GetText(xml, "ba");
            //GetText(xml, "ka");
            //GetText(xml, "ko");
            //GetText(xml, "fa");
            GetText(xml, "ab");
        }
    });
    tStatusTest = setTimeout("StatusCheckTest()", 30000);
}

function init_city_search() {
    $().ready(function () {
        $("#city_search").autocomplete("/xml/c.aspx", {
            selectFirst: false,
            max: 20,
            delay: 300,
            //autoFill: true,
            mustMatch: true,
            extraParams: {
                c: $('#country').val(),
                r: $('#region').val()
            }
        });

        $("#city_search").result(function (event, data, formatted) {
            if (data)
                $('#city').val(data[1]);
        });
    });
}

function changeQuery() {
    $("#city_search").val('');
    $('#city').val(0);
    $("#city_search").setOptions({
        extraParams: {
            c: $('#country').val(),
            r: $('#region').val()
        }
    });
}


/*function qf(t) {
    if (t.value == 'Snabbsök...') {
        t.value = '';
        t.style.color = 'black';
    }
}

function qb(t) {
    if (t.value == '') {
        t.value = 'Snabbsök...';
        t.style.color = 'gray';
    }
}*/

/*function fp(p, d) {
    return overlib('<img src="' + p + '.jpg" class="img0">', VAUTO, WIDTH, -1, HEIGHT, -1, DELAY, d);
}*/


/*
* TipTip
* Copyright 2010 Drew Wilson
* www.drewwilson.com
* code.drewwilson.com/entry/tiptip-jquery-plugin
*
* Version 1.2   -   Updated: Jan. 13, 2010
*
* This Plug-In will create a custom tooltip to replace the default
* browser tooltip. It is extremely lightweight and very smart in
* that it detects the edges of the browser window and will make sure
* the tooltip stays within the current window size. As a result the
* tooltip will adjust itself to be displayed above, below, to the left 
* or to the right depending on what is necessary to stay within the
* browser window. It is completely customizable as well via CSS.
*
* This TipTip jQuery plug-in is dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*/

(function($) {
    $.fn.tipTip = function(options) {
        var defaults = {
            maxWidth: "200px",
            edgeOffset: 6,
            delay: 400,
            fadeIn: 100,
            fadeOut: 100,
            extraStart: "",
            extraEnd: "",
            enter: function() { },
            exit: function() { }
        };
        var opts = $.extend(defaults, options);

        // Setup tip tip elements and render them to the DOM
        if ($("#tiptip_holder").length <= 0) {
            var tiptip_holder = $('<div id="tiptip_holder" style="max-width:' + opts.maxWidth + ';"></div>');
            var tiptip_content = $('<div id="tiptip_content"></div>');
            var tiptip_arrow = $('<div id="tiptip_arrow"></div>');
            $("body").append(tiptip_holder.html(tiptip_content).prepend(tiptip_arrow.html('<div id="tiptip_arrow_inner"></div>')));
        } else {
            var tiptip_holder = $("#tiptip_holder");
            var tiptip_content = $("#tiptip_content");
            var tiptip_arrow = $("#tiptip_arrow");
        }

        return this.each(function() {
            var org_elem = $(this);
            var org_title = org_elem.attr("title");
            if (org_title != "") {
                org_title = opts.extraStart + org_title + opts.extraEnd;
                org_elem.removeAttr("title"); //remove original Title attribute
                var timeout = false;
                org_elem.hover(function() {
                    opts.enter.call(this);
                    tiptip_content.html(org_title);
                    tiptip_holder.hide().removeAttr("class").css("margin", "0");
                    tiptip_arrow.removeAttr("style");

                    var top = parseInt(org_elem.offset()['top']);
                    var left = parseInt(org_elem.offset()['left']);
                    var org_width = parseInt(org_elem.outerWidth());
                    var org_height = parseInt(org_elem.outerHeight());
                    var tip_w = tiptip_holder.outerWidth();
                    var tip_h = tiptip_holder.outerHeight();
                    var w_compare = Math.round((org_width - tip_w) / 2);
                    var h_compare = Math.round((org_height - tip_h) / 2);
                    var marg_left = Math.round(left + w_compare);
                    var marg_top = Math.round(top + org_height + opts.edgeOffset);
                    var t_class = "";
                    var arrow_top = "";
                    var arrow_left = Math.round(tip_w - 12) / 2;

                    if (w_compare < 0) {
                        if ((w_compare + left) < parseInt($(window).scrollLeft())) {
                            t_class = "_right";
                            arrow_top = Math.round(tip_h - 13) / 2;
                            arrow_left = -12;
                            marg_left = Math.round(left + org_width + opts.edgeOffset);
                            marg_top = Math.round(top + h_compare);
                        } else if ((tip_w + left) > parseInt($(window).width())) {
                            t_class = "_left";
                            arrow_top = Math.round(tip_h - 13) / 2;
                            arrow_left = Math.round(tip_w);
                            marg_left = Math.round(left - (tip_w + opts.edgeOffset + 5));
                            marg_top = Math.round(top + h_compare);
                        }
                    }
                    if ((top + org_height + opts.edgeOffset + tip_h + 8) > parseInt($(window).height() + $(window).scrollTop())) {
                        t_class = t_class + "_top";
                        arrow_top = tip_h;
                        marg_top = Math.round(top - (tip_h + 5 + opts.edgeOffset));
                    } else if (((top + org_height) - (opts.edgeOffset + tip_h)) < 0 || t_class == "") {
                        t_class = t_class + "_bottom";
                        arrow_top = -12;
                        marg_top = Math.round(top + org_height + opts.edgeOffset);
                    }
                    if (t_class == "_right_top" || t_class == "_left_top") {
                        marg_top = marg_top + 5;
                    } else if (t_class == "_right_bottom" || t_class == "_left_bottom") {
                        marg_top = marg_top - 5;
                    }
                    if (t_class == "_left_top" || t_class == "_left_bottom") {
                        marg_left = marg_left + 5;
                    }
                    tiptip_arrow.css({ "margin-left": arrow_left + "px", "margin-top": arrow_top + "px" });
                    tiptip_holder.css({ "margin-left": marg_left + "px", "margin-top": marg_top + "px" }).attr("class", "tip" + t_class);

                    if (timeout) { clearTimeout(timeout); }
                    timeout = setTimeout(function() { tiptip_holder.stop(true, true).fadeIn(opts.fadeIn); }, opts.delay);
                }, function() {
                    opts.exit.call(this);
                    if (timeout) { clearTimeout(timeout); }
                    tiptip_holder.fadeOut(opts.fadeOut);
                });
            }
        });
    }
})(jQuery);


function ad_error() {
    newwindow = window.open('/admin/techsupport.aspx', 'ad_popfb', 'height=270,width=500');
    if (window.focus) { newwindow.focus() }
    return false;
}


//Temp
function fb(p, t) {
    newwindow = window.open('/feedback/default.aspx?t=' + t + '&p=' + p, 'popfb', 'height=300,width=500');
    if (window.focus) { newwindow.focus() }
    return false;
}
