/*
** CoverVil Javascript.
** All rights reserved.
**
** Created by Bil Software, www.bilsoftware.com, 2010
*/

function $(i) { return document.getElementById(i); }

var IE     = document.all ? true : false;
var IE6    = parseInt(navigator.appVersion.split('MSIE')[1]) == 6;
var IE67   = parseInt(navigator.appVersion.split('MSIE')[1]) <= 7;
var Opera  = window.opera ? true : false;
var Chrome = navigator.userAgent.indexOf('Chrome') != -1;
var rating = 0;
var old_rating = 0;

function change(enable) {
    for (var i = 1; i < arguments.length; ++i) {
        $(arguments[i]).disabled = !enable;
        if (IE) {
            if (!enable) $(arguments[i]).className += ' disabled';
            else $(arguments[i]).className = $(arguments[i]).className.replace(' disabled', '');
        }
    }
}

function getMouseXY(e) {
    if (IE) {
        tempX = event.clientX + document.body.scrollLeft;
        tempY = event.clientY + document.body.scrollTop;
    } else {
        tempX = e.pageX;
        tempY = e.pageY;
    }
    return [Math.max(0, tempX), Math.max(0, tempY)];
}
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft;
        curtop = obj.offsetTop;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
    }
    return [curleft, curtop];
}

function getLeft(obj) {
    return findPos(obj)[0];
}
function getTop(obj) {
    return findPos(obj)[1];
}

function set_cookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());

    if (expires) expires = expires * 1000 * 60 * 60 * 24;

    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
					((expires) ? ";expires=" + expires_date.toGMTString() : "") +
					((path) ? ";path=" + path : "") +
					((domain) ? ";domain=" + domain : "") +
					((secure) ? ";secure" : "");
}

function showHide(el, show) {
    el.style.display = show ? '' : 'none';
}

function st() {
    if ($('container')) {
        $('container').onmousemove = rating_mousemove;
        $('container').onclick = rating_click;
        $('container').onmouseout = rating_mouseout;
        old_rating = parseFloat($('rating').style.width.replace('px', '')) / 16;
    }
}

function request(plik) {
    if (window.XMLHttpRequest) obj = new XMLHttpRequest();
    else if (window.ActiveXObject) obj = new ActiveXObject('Microsoft.XMLHTTP');
    else return false;

    obj.open('GET', plik, false);
    obj.send(null);

    if (obj.readyState == 4) return obj.responseText;
    else return false;
}

function rating_mousemove(ev) {
    ev = ev || window.event;
    var pos = 0;
    if (ev.pageX) pos = ev.pageX;
    else pos = ev.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    pos -= getLeft($('rating'));
    pos += 4;
    var rat = pos / 16;
    if (rat > 5 || rat <= 0) return;
    if (rat % 0.5 == 0) {
        rating = rat;
        $('rating').style.width = pos + 'px';
    }
}
function rating_click() {
    location.hash = '';
    var loc = location.href.replace('#', '');

    if (rating <= 0) return;
    var sep = '&';
    if (loc.indexOf('?') == -1) sep = '?';
    var response = request(loc + sep + 'rate=' + rating);

    if (response.indexOf('|') != -1) {
        response = response.split('|');
        old_rating = parseFloat(response[0]);
        $('rating').style.width = (old_rating * 16) + 'px';
        rating = 0;
        alert(response[1]);
    } else alert(response);
}
function rating_mouseout(ev) {
    ev = ev || window.event;
    var posx = 0, posy = 0;
    if (ev.pageX) posx = ev.pageX;
    else posx = ev.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);

    if (ev.pageY) posy = ev.pageY;
    else posy = ev.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    if (posx >= getLeft($('container')) + 80 || posx < getLeft($('container'))
	|| posy >= getTop($('container')) + 16 || posy < getTop($('container'))) {
        $('rating').style.width = (old_rating * 16) + 'px';
        rating = 0;
    }
}

function Prepare(el, text) {
    var tooltip, b, s, l;
    tooltip = document.createElement('span');
    tooltip.className = 'tooltip';
    tooltip.innerHTML = text;
    el.tooltip = tooltip;
    el.onmouseover = function (e) {
        $('btc').appendChild(this.tooltip);
        Locate(e);
    }
    el.onmouseout = function () {
        if ($('btc').childNodes.length > 0) $('btc').removeChild($('btc').firstChild);
    }
    el.onmousemove = Locate;
}
function RemoveTooltip(el) {
    if (el.tooltip) {
        el.tooltip = null;
        el.onmouseover = null;
        el.onmouseout = null;
        el.onmousemove = null;
    }
}

function Locate(e) {
    var posx = 0, posy = 0;
    if (e == null) e = window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX;
        posy = e.pageY;
    } else if (e.clientX || e.clientY) {
        if (document.documentElement.scrollTop) {
            posx = e.clientX + document.documentElement.scrollLeft;
            posy = e.clientY + document.documentElement.scrollTop;
        } else {
            posx = e.clientX + document.body.scrollLeft;
            posy = e.clientY + document.body.scrollTop;
        }
    }
    $('btc').style.top = (posy + 8) + 'px';
    $('btc').style.zIndex = 999;
    $('btc').style.left = posx + 12/* - Math.round($('btc').offsetWidth / 2) */ + 'px';
}

function get_elements_by_class(cn, root) {
    if (!root) root = document;
    var queue = new Array();
    queue.push(root);
    var ret = new Array();
    while (queue.length > 0) {
        element = queue.pop();
        if (element.className) {
            var classes = element.className.split(' ');
            if (IE) {
                for (var i in classes) if (classes[i] == cn) ret.push(element);
            } else {
                if (classes.indexOf(cn) != -1) ret.push(element);
            }
        }
        if (element.childNodes != null) {
            if (element.childNodes.length > 0) {
                for (i = 0; i < element.childNodes.length; i++) {
                    queue.push(element.childNodes[i]);
                }
            }
        }
    }
    return ret;
}

var p = 1.0009;
var a = 50;
var s = 0.00000001;
var fps = 25;
function setOpacity(el, op) {
    if (op == 100) opacity = '1.0';
    else if (op < 10) opacity = '0.0' + op;
    else opacity = '0.' + op;
    el.style.filter = 'alpha(opacity=' + op + ')';
    el.style.KHTMLOpacity = opacity;
    el.style.MozOpacity = opacity;
    el.style.opacity = opacity;
}
function inOutQuint(t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; }
function slide(element, sourceHeight, targetHeight, sourceOpacity, targetOpacity, time, forceOneWay, elapsed) {
    var back = false;

    if (!sourceHeight && !targetHeight) {
        targetHeight = getDimensions(element).height;
    }

    if (!elapsed) {
        elapsed = 0;
        if (!forceOneWay) {
            back = Math.round(parseFloat($(element).style.height.replace('px', ''))) == targetHeight;
            if ($(element).offsetHeight > 0 && $(element).style.height == '') back = true;
        }
        $(element).style.display = /*back?'none':*/'block';
    }

    if (back) {
        var tmp = sourceHeight;
        sourceHeight = targetHeight;
        targetHeight = tmp;

        tmp = sourceOpacity;
        sourceOpacity = targetOpacity;
        targetOpacity = tmp;
    }
    var destHeight = targetHeight - sourceHeight;
    var destOpacity = targetOpacity - sourceOpacity;

    var newHeight = inOutQuint(elapsed, sourceHeight, destHeight, time);
    var newOpacity = Math.round(inOutQuint(elapsed, sourceOpacity, destOpacity, time));
    if (elapsed <= time) {
        if ($(element)) {
            $(element).style.height = newHeight + 'px';

            elapsed += 1000 / fps;
            setTimeout('slide(\'' + element + '\', ' + sourceHeight + ', ' + targetHeight + ', ' + sourceOpacity + ', ' + targetOpacity + ', ' + time + ', ' + forceOneWay + ', ' + elapsed + ')', 1000 / fps);

            setOpacity($(element), newOpacity);
        }
        //window.scroll(0, 5000);
    } else {
        if ($(element)) {
            $(element).style.height = targetHeight + 'px';

            $(element).style.display = Math.round(parseFloat($(element).style.height.replace('px', ''))) == 0 ? 'none' : 'block';
            if (targetHeight == 0) $(element).style.display = 'none';
            //setOpacity($(element), 100);
        }
    }
}
function fade(element, sourceOpacity, targetOpacity, time, fade, elapsed) {
    var back = fade == 'out';
    if (!elapsed) elapsed = 0;

    if (back) {
        var tmp = sourceOpacity;
        sourceOpacity = targetOpacity;
        targetOpacity = tmp;
    }
    var destOpacity = targetOpacity - sourceOpacity;

    var newOpacity = Math.round(inOutQuint(elapsed, sourceOpacity, destOpacity, time));
    if (elapsed <= time) {
        setOpacity($(element), newOpacity);
        elapsed += 1000 / fps;
        setTimeout('fade(\'' + element + '\', ' + sourceOpacity + ', ' + targetOpacity + ', ' + time + ', \'' + fade + '\', ' + elapsed + ')', 1000 / fps);
    } else {
        //setOpacity($(element), 100);
    }
}

function execCmd(id, cmd, param) {
    switch (cmd) {
        case 'link':
            var url = prompt('Podaj adres URL linku', 'http://');
            if (url != null && url != '') {
                $(id + '_iframe').contentWindow.document.execCommand('CreateLink', false, url);
            }
            break;
        case 'img':
            var url = prompt('Podaj adres URL obrazka', 'http://');
            if (url != null && url != '') {
                $(id + '_iframe').contentWindow.document.execCommand('InsertImage', false, url);
            }
            break;
        default: $(id + '_iframe').contentWindow.document.execCommand(cmd, false, param); break;
    }
    return false;
}
function strip_tags(str, allowed_tags) {
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';

    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
    if (allowed_tags) allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);

    str += '';
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    for (key in matches) {
        if (isNaN(key)) continue;
        html = matches[key].toString();
        allowed = false;
        for (k in allowed_array) {
            allowed_tag = allowed_array[k];
            i = -1;
            if (i != 0) { i = html.toLowerCase().indexOf('<' + allowed_tag + '>'); }
            if (i != 0) { i = html.toLowerCase().indexOf('<' + allowed_tag + ' '); }
            if (i != 0) { i = html.toLowerCase().indexOf('</' + allowed_tag); }
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) str = replacer(html, "", str);
    }

    return str;
}

function rgb2hex(s) {
    s = s.replace('rgb(', '').replace(')', '').replace(/\s/g, '').split(',');
    var ret = '';
    for (var i = 0; i < 3; i++) ret += parseInt(s[i]).toString(16).replace(/^([\da-f])$/, "0$1");
    return '#' + ret;
}
function Xhtmlize(html) {
    html = html.replace(/<(.*?)>/g, function (w) { return w.toLowerCase(); });
    html = html.replace(/(rgb\(\d+,\s?\d+,\s?\d+\))/g, rgb2hex);
    /*html = html.replace(/(<\/font>)/g, '</span>');
    html = html.replace(/font color=\"(.*?)\"/g, 'span style="color: $1"');
    html = html.replace(/<br>/gi, '<br />');
    html = html.replace(/<meta(.|\n)*<\/style>/gi, '');
    html = html.replace(/<script(.|\n)*<\/script>/gi, '');
    html = html.replace(/javascript:/gi, '');
    html = html.replace(/mso\-.*?\-/gi, '');
    html = html.replace(/ style=\"\"/gi, '');
    html = html.replace(/ class=\"msonormal\"/gi, '');
    html = html.replace(/<!\-?\-?\[if\s(.|\n)*?\]\-\->/gi, '');
    html = html.replace(/\n\n/gi, '\n');
    html = html.replace(/<(.*?)>/g, function(w){return w.toLowerCase();});*/
    //alert(html);
    html = strip_tags(html, '<b><strong><i><u><ol><ul><li><p><a><div><br><span><em>');
    html = html.replace(/javascript:/gi, '');

    html = html.replace(/</g, '[[');
    html = html.replace(/>/g, ']]');

    return html;
}
function Xhtmlize2(html) {
    html = html.replace(/<(.*?)>/g, function (w) { return w.toLowerCase(); });
    html = html.replace(/(rgb\(\d+,\s?\d+,\s?\d+\))/g, rgb2hex);
    html = strip_tags(html, '<b><strong><i><u><ol><ul><li><p><a><div><br><span><em>');
    html = html.replace(/javascript:/gi, '');
    return html;
}
var textAreas = new Array();
function updateAllTextareas() {
    for (var i in textAreas) {
        $(textAreas[i]).value = Xhtmlize($(textAreas[i] + '_iframe').contentWindow.document.body.innerHTML);
    }
}
function updateAllTextareas2() {
    /*for(var i in textAreas){
    $(textAreas[i]).value = Xhtmlize2($(textAreas[i] + '_iframe').contentWindow.document.body.innerHTML);
    $(textAreas[i] + '_iframe').contentWindow.document.body.innerHTML = $(textAreas[i]).value;
    }*/
}
function createButtons(id) {
    var buttonsBG = document.createElement('div');
    //alert($(id).style.width);
    //buttonsBG.style.width = parseInt($(id).style.width.replace('px','')) - 7 + 'px';
    //buttonsBG.style.margin = $(id).style.margin;
    buttonsBG.className = 'icons';
    $(id).parentNode.appendChild(buttonsBG);

    var buttons2 = new Array();
    /*
    var select = document.createElement('select');
    for(var i = 1; i < 8; i++){
    var option = document.createElement('option');
    select.appendChild(option);
    buttons2.push(option);
    }
    buttons2[0].onclick = function(){return execCmd(id, 'fontSize', 1);}; buttons2[0].innerHTML = '8';
    buttons2[1].onclick = function(){return execCmd(id, 'fontSize', 2);}; buttons2[1].innerHTML = '10';
    buttons2[2].onclick = function(){return execCmd(id, 'fontSize', 3);}; buttons2[2].innerHTML = '11'; buttons2[2].selected = true;
    buttons2[3].onclick = function(){return execCmd(id, 'fontSize', 4);}; buttons2[3].innerHTML = '14';
    buttons2[4].onclick = function(){return execCmd(id, 'fontSize', 5);}; buttons2[4].innerHTML = '18';
    buttons2[5].onclick = function(){return execCmd(id, 'fontSize', 6);}; buttons2[5].innerHTML = '24';
    buttons2[6].onclick = function(){return execCmd(id, 'fontSize', 7);}; buttons2[6].innerHTML = '36';
    buttonsBG.appendChild(select);
    */
    var buttons = [
		{ title: 'Pogrubienie',             text: 'B',    id: 'bold' },
		{ title: 'Pochylenie',              text: 'I',    id: 'italic' },
		{ title: 'Podkreślenie',            text: 'U',    id: 'underline' },
		{ title: 'Wyrównanie do lewej',     text: '<-',   id: 'justifyleft' },
		{ title: 'Wyrównanie do środka',    text: '-',    id: 'justifycenter' },
		{ title: 'Wyrównanie do prawej',    text: '->',   id: 'justifyright' },
		{ title: 'Wyrównanie do obu stron', text: '<->',  id: 'justifyfull' },
		{ title: 'Wstaw listę numerowaną',  text: 'ol',   id: 'insertorderedlist' },
		{ title: 'Wstaw listę punktowaną',  text: 'ul',   id: 'insertunorderedlist' },
		{ title: 'Wstaw link',              text: 'link', id: 'link' }
	];

    buttons2 = new Array();

    for (var i in buttons) {
        var btn = document.createElement('button');
        btn.title = buttons[i].title;
        btn.className = buttons[i].id;
        btn.innerHTML = buttons[i].text;
        buttonsBG.appendChild(btn);
        buttons2.push(btn);
    }
    buttons2[0].onclick = function () { return execCmd(id, 'bold'); };
    buttons2[1].onclick = function () { return execCmd(id, 'italic'); };
    buttons2[2].onclick = function () { return execCmd(id, 'underline'); };
    buttons2[3].onclick = function () { return execCmd(id, 'justifyleft'); };
    buttons2[4].onclick = function () { return execCmd(id, 'justifycenter'); };
    buttons2[5].onclick = function () { return execCmd(id, 'justifyright'); };
    buttons2[6].onclick = function () { return execCmd(id, 'justifyfull'); };
    buttons2[7].onclick = function () { return execCmd(id, 'insertorderedlist'); };
    buttons2[8].onclick = function () { return execCmd(id, 'insertunorderedlist'); };
    buttons2[9].onclick = function () { return execCmd(id, 'link'); };
}
var updateInterval = 0;
function initWYSIWYG(id) {
    if ($(id)) {
        createButtons(id);

        var iframe = document.createElement('iframe');
        iframe.id = id + '_iframe';
        iframe.style.marginTop = '0';
        $(id).style.display = 'none';
        $(id).parentNode.appendChild(iframe);
        textAreas.push(id);
        if (!updateInterval) updateInterval = setInterval('updateAllTextareas2()', 1000);

        var ifr_doc = $(id + '_iframe').contentWindow.document;
        ifr_doc.open();
        ifr_doc.write('<html><head></head><body style="padding: 15px;margin:0;font: 12px Tahoma; ">' + $(id).value + '</body></html>');
        ifr_doc.close();

        if (IE) ifr_doc.body.contentEditable = true;
        else ifr_doc.designMode = 'on';
    }
}
//UPLOADER
function getDimensions(element) {
    element = $(element);
    var display = element.style.display;
    if (display != 'none' && display != null) // Safari bug
        return { width: element.offsetWidth, height: element.offsetHeight };

    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition   = els.position;
    var originalDisplay    = els.display;
    els.visibility         = 'hidden';
    els.position           = 'absolute';
    els.display            = 'block';
    var originalWidth      = element.clientWidth || element.scrollWidth;
    var originalHeight     = element.clientHeight || element.scrollHeight;
    els.display            = originalDisplay;
    els.position           = originalPosition;
    els.visibility         = originalVisibility;
    return { width: originalWidth, height: originalHeight };
}
function size_readable(size) {
    c = 0;
    format = new Array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    while ((size / 1024) > 1 && c < 8) {
        size /= 1024;
        c++;
    }
    size += '';
    if (size.indexOf('.') <= 0 && c > 1) {
        size += ',00';
    }
    if (size.indexOf('.') > 0) {
        dk = size.substring(0, size.indexOf('.'));
        pk = size.substring(size.indexOf('.') + 1, size.indexOf('.') + 3);
        if (pk.length == 1) pk += '0';
        size = dk + ',' + pk;
    }
    return size + ' ' + format[c];
}
function send(plik, post) {
    if (window.XMLHttpRequest) obj = new XMLHttpRequest();
    else if (window.ActiveXObject) obj = new ActiveXObject('Microsoft.XMLHTTP');
    else return false;
    obj.open('POST', plik, false);
    obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
    obj.send(post);
    if (obj.readyState == 4) return obj.responseText;
    else return false;
}

//#region -------------------------Uploader-------------------------
function UploadSetName(name) {
    $('fileinput').innerHTML = name;
}

function UploadComplete(response) {
    fade('progresscontainer', 100, 0, 500, 'in');
    $('fileinput').innerHTML = '';
    $('submitPic').disabled = false;

    /*var values = response.split(';##;');
    if(values.length < 3){
    alert('Wystąpił błąd - ' + response);
    return;
    }*/

    //continue form
    //alert('upload complete');
    $('imghash').value = response;
    $('upload_form').submit();
}
function StartUpload() {
    if ($('upload_form').url && $('upload_form').url.value.length > 4) $('upload_form').submit();
    else $('flash_uploader').SetVariable('upload', 1);
    return false;
}
function UploadStart() {
    fade('progresscontainer', 0, 100, 500, 'in');
    $('progress').style.width = '0px';
    $('submitPic').disabled = true;
}
function UploadProgress(procent, przeslane, calosc, predkosc, name) {
    $('progress').style.width = procent + '%';
    $('fileinput').innerHTML = name + ' - ' + procent + '%' + ' (' + size_readable(predkosc) + '/s)';
}
//#endregion

function externalLinks() {
    if (!document.getElementsByTagName) return;

    var anchors = document.getElementsByTagName("a");

    for (var i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        var relvalue = anchor.getAttribute("rel");

        if (anchor.getAttribute("href")) {
            var external = /external/;
            relvalue = anchor.getAttribute("rel");
            if (external.test(relvalue)) { anchor.target = "_blank"; }
        }
    }
}

function adding_validate() {
    var f = $('upload_form');
    var conditions = [[f.title.value == '', 'Podaj tytuł', f.title.parentNode.parentNode],
                      [f.category.value <= 0, 'Wybierz kategorię', f.category.parentNode.parentNode]];
    var ok = true;
    for (var i in conditions) {
        if (conditions[i][0]) {
            ok = false;
            if (conditions[i][2].className.indexOf('error ov') == -1) {
                conditions[i][2].className += 'error ov';
            }
            conditions[i][2].title = conditions[i][1];
        } else {
            conditions[i][2].className = conditions[i][2].className.replace('error ov', '');
            conditions[i][2].title = '';
            RemoveTooltip(conditions[i][2]);
        }
    }
    init_tooltips();
	return ok;

}

function init_tooltips() {
    var elems = get_elements_by_class('ov');
    for (var i = 0; i < elems.length; ++i) {
        Prepare(elems[i], elems[i].getAttribute('title'));
        elems[i].setAttribute('title', '');
    }
}

function reg_rules(sel) {
    if (sel.value == 1) $('rules_link').href = 'zostan_grafikiem_wyslij_swoje_pliki-s43.html';
    else                $('rules_link').href = 'zostan_czlonkiem_spolecznosci_covervil-s44.html';
}

window.onload = function () {
    st();

    var h = document.createElement('span');
    h.id = 'btc';
    h.setAttribute('id', 'btc');
    h.style.position = 'absolute';
    document.getElementsByTagName('body')[0].appendChild(h);

    init_tooltips();
    externalLinks();
}
