﻿var ajax = new xhr();
var blob = new Blob();
var scroller = null;

function Blob() {

    var obj = this;
    var flashvars, params, attributes;    
    this.id = null;
    this.name = null;

    this.init = function(id, name, mode) {
        this.id = id;
        this.name = name;
        ajax.requestFile = "xhr.ashx?action=check&id=" + this.id;
        ajax.onLoading = function() { };
        ajax.onCompletion = function() {
            if (mode == "v") {
                obj.view(ajax.response);
            } else {
                obj.download(ajax.response);
            }
        };
        ajax.runAJAX();
    };

    this.view = function(msg) {
        switch (obj.name.substr(obj.name.lastIndexOf(".") + 1).toLowerCase()) {
            case "jpg": case "jpeg": case "gif": case "png": case "swf":
                flashvars = { autoStart: "false", imageFile: obj.name, imageInfo: "<P ALIGN='CENTER'><FONT FACE='Verdana' SIZE='11' COLOR='#F0F0F0' LETTERSPACING='0' KERNING='0'>" + msg + "</FONT></P>" };
                params = { allowScriptAccess: "always", allowFullScreen: "true", bgcolor: "#0f0f0f" };
                attributes = { id: "blob-viewer", name: "blob-viewer" };
                swfobject.embedSWF("includes/imageViewer.swf", "blob-viewer", "320", "240", "9.0.0", "includes/expressInstall.swf", flashvars, params, attributes);
                break;
            case "mp3":
                flashvars = { autoStart: "false", soundFile: obj.name, soundInfo: "<P ALIGN='CENTER'><FONT FACE='Verdana' SIZE='11' COLOR='#F0F0F0' LETTERSPACING='0' KERNING='0'>" + msg + "</FONT></P>" };
                params = { allowScriptAccess: "always", bgcolor: "#0f0f0f" };
                attributes = { id: "blob-viewer", name: "blob-viewer" };
                swfobject.embedSWF("includes/soundPlayer.swf", "blob-viewer", "320", "240", "9.0.0", "includes/expressInstall.swf", flashvars, params, attributes);
                break;
            case "flv": case "f4v": case "mp4":
                flashvars = { autoStart: "false", videoFile: obj.name, videoInfo: "<P ALIGN='CENTER'><FONT FACE='Verdana' SIZE='11' COLOR='#F0F0F0' LETTERSPACING='0' KERNING='0'>" + msg + "</FONT></P>" };
                params = { allowScriptAccess: "always", allowFullScreen: "true", bgcolor: "#0f0f0f" };
                attributes = { id: "blob-viewer", name: "blob-viewer" };
                swfobject.embedSWF("includes/videoPlayer.swf", "blob-viewer", "320", "240", "9.0.0", "includes/expressInstall.swf", flashvars, params, attributes);
                break;
            default:
                flashvars = { autoStart: "false", fileName: obj.name, fileInfo: "<P ALIGN='CENTER'><FONT FACE='Verdana' SIZE='11' COLOR='#F0F0F0' LETTERSPACING='0' KERNING='0'>" + msg + "</FONT></P>" };
                params = { allowScriptAccess: "always", bgcolor: "#0f0f0f" };
                attributes = { id: "blob-viewer", name: "blob-viewer" };
                swfobject.embedSWF("includes/downloader.swf", "blob-viewer", "320", "240", "9.0.0", "includes/expressInstall.swf", flashvars, params, attributes);
                break;
        }
    };

    this.download = function(msg) {
        flashvars = { autoStart: "false", fileName: obj.name, fileInfo: "<P ALIGN='CENTER'><FONT FACE='Verdana' SIZE='11' COLOR='#F0F0F0' LETTERSPACING='0' KERNING='0'>" + msg + "</FONT></P>" };
        params = { allowScriptAccess: "always", bgcolor: "#0f0f0f" };
        attributes = { id: "blob-viewer", name: "blob-viewer" };
        swfobject.embedSWF("includes/downloader.swf", "blob-viewer", "320", "240", "9.0.0", "includes/expressInstall.swf", flashvars, params, attributes);
    };

    this.log = function() {
        ajax.requestFile = "xhr.ashx?action=log&id=" + obj.id;
        ajax.onLoading = function() { };
        ajax.onCompletion = function() {
            if (ajax.response != "null") {
                document.getElementById('feedback').style.visibility = 'visible'
                document.getElementById('feedback').innerHTML = ajax.response;
                setTimeout("document.getElementById('feedback').style.visibility = 'hidden';", 7000);
            }
        };
        ajax.runAJAX();
    };
    
    this.add_field = function(){
        var target = document.getElementById('blob-form').upload_mode;
        for (var i = 0; i < target.length; i++) {
            if (target[i].checked) {
                val = target[i].value;
            }
        }
        var tbody = document.getElementById('blob').getElementsByTagName('TBODY')[0];
        var tr = document.createElement('TR');
        var td = document.createElement('TD');
        td.setAttribute('colSpan', '2');
        var input = document.createElement('INPUT');
        input.name = 'blob_file';
        input.style.width = '300px';
        input.type = (val == 1) ? 'file' : 'text';
        td.appendChild(input);
        tr.appendChild(td);
        td = document.createElement('TD');
        var a = document.createElement('A')
        a.href = 'javascript:void(0)';
        a.onclick = function() { obj.remove_field(this); };
        a.innerHTML = '[-]';
        td.appendChild(a);
        tr.appendChild(td)
        tbody.appendChild(tr);    
    };

    this.remove_field = function(target) {
        var tbody = document.getElementById('blob').getElementsByTagName('TBODY')[0];
        var tr = target.parentNode.parentNode;
        tr.parentNode.removeChild(tr);
    };
}

function getFlashMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1; return (isIE) ? window[movieName] : document[movieName];
}

function responseToAS() {
    var text = "hello actionScript";
    getFlashMovie("imageViewer").responseFromJS(text);
}

function responseFromAS(response) {
    blob.log();
}

function change(obj) {
    if (obj.checked) {
        document.getElementById("password").disabled = false;
        document.getElementById("password").className = "textbox";
    } else {
        document.getElementById("password").value = "";
        document.getElementById("password").disabled = true;
        document.getElementById("password").className = "disabled";
    }
}

function switch_tab(tab, flag, type) {
    var i = null;
    if (flag != null) {
        var header = tab.parentNode.getElementsByTagName('LI');
        for (i = 0; i < header.length; i++) {
            if (header[i].className == ('tab_h_active_' + type)) {
                header[i].className = ('tab_h_inactive_' + type);
            }
            if (header[i] == tab) {
                header[i].className = ('tab_h_active_' + type);
                var handler = i;
            }
        }
        var index = 0;
        var content = tab.parentNode.parentNode.childNodes;
        for (i = 0; i < content.length; i++) {
            if (content[i].nodeName == 'DIV') {
                if (content[i].className == ('tab_c_active_' + type)) {
                    content[i].className = ('tab_c_inactive_' + type)
                }
                if (index == handler) {
                    content[i].className = ('tab_c_active_' + type)
                } 
                index++
            }
        }
    } else {
        var tabs = document.getElementById(tab).parentNode.getElementsByTagName('LI');
        for (i = 0; i < tabs.length; i++) {
            if (tabs[i].className == 'tab_h_active_a') {
                tabs[i].className = 'tab_h_inactive_a';
                document.getElementById(tabs[i].id.replace(/h/, 'c')).className = 'tab_c_inactive_a';
            }
            if (tabs[i].id == tab) {
                tabs[i].className = 'tab_h_active_a';
                document.getElementById(tabs[i].id.replace(/h/, 'c')).className = 'tab_c_active_a';
            }
        }
    } 
}

function switch_upload_mode(val) {
    var tbody = document.getElementById('blob').getElementsByTagName('TBODY')[0];
    var inputs = tbody.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].name == 'blob_file') {
            var input = document.createElement('INPUT');
            input.name = 'blob_file';
            input.type = (inputs[i].type == 'text') ? 'file' : 'text';
            inputs[i].parentNode.replaceChild(input, inputs[i]);            
        }
    }
}

function switch_members_area() {
    var login_box = document.getElementById('login-form');
    var password_box = document.getElementById('password-form');
    if (login_box.style.display == 'none') {
        login_box.style.display = 'block';
        login_box.style.visibility = 'visible';
        password_box.style.display = 'none';
        password_box.style.visibility = 'hidden';
    } else {
        login_box.style.display = 'none';
        login_box.style.visibility = 'hidden';
        password_box.style.display = 'block';
        password_box.style.visibility = 'visible';
    }
}

var the_months = ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"];
var the_days = ["P", "U", "S", "Č", "F", "S", "N"];
var days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var one_day = 1000 * 60 * 60 * 24; 
var date_format = 'd.m.y';

function ooCalendar(box, beginning_date, ending_date) {
if (document.getElementById('calendar')) return false;
var obj = this;
var pattern_dmy = new RegExp('\\d{1,2}-\\d{1,2}-\\d{4}');
var pattern_ymd = new RegExp('\\d{4}-\\d{1,2}-\\d{1,2}');
this.i_int = null; this.d_int = null;
this.box = box;
if (beginning_date != null || ending_date != null) {
if (beginning_date != null) {
this.beginning_date = beginning_date.replace(/-/g, '');
} else {
this.beginning_date = new Date();
this.beginning_date = this.beginning_date.format('ymd');
} if (ending_date != null) { this.ending_date = ending_date.replace(/-/g, ''); } else {
this.ending_date = new Date(this.beginning_date.substr(0, 4), (this.beginning_date.substr(4, 2) - 1), this.beginning_date.substr(6, 2)); 
this.ending_date.setTime(Math.ceil(this.ending_date.getTime() + (one_day * 180))); 
this.ending_date = this.ending_date.format('ymd'); }
} else { this.beginning_date = 0; this.ending_date = 99999999; } if ((this.box.value != '') && pattern_dmy.test(this.box.value)) {
var box_date = this.box.value.split('-'); 
this.current_date = new Date(box_date[2], (box_date[1] - 1), box_date[0]); 
} else if ((this.box.value != '') && pattern_ymd.test(this.box.value)) {
box_date = this.box.value.split('-');
this.current_date = new Date(box_date[0], (box_date[1] - 1), box_date[2]);
} else { this.current_date = new Date(); } this.current_year = this.current_date.getFullYear(); this.current_month = this.current_date.getMonth(); 
this.current_day = this.current_date.getDate(); 
this.initialize_calendar = function() {
this.the_first_of_current_month = new Date(this.current_year, this.current_month, 1);
this.first_day_index = ((this.the_first_of_current_month.getDay() - 1) == -1) ? 6 : (this.the_first_of_current_month.getDay() - 1); 
this.length_of_current_month = (days_in_month[this.current_month] == 28) ? ((this.current_year % 400 == 0 || (this.current_year % 4 == 0 && this.current_year % 100 != 0)) ? 29 : 28) : days_in_month[this.current_month];
this.needed_rows = Math.ceil((this.length_of_current_month + this.first_day_index) / 7);
}; 

this.rebuild_calendar_body = function(o, month, year, e) {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation(); 
    if (month) {
        this.current_month = parseInt(o.id.substr(o.id.indexOf('_') + 1));
        this.month_chooser.innerHTML = the_months[this.current_month]; this.month_chooser.id = 'c' + o.id; 
        this.months.parentNode.removeChild(this.months);
    } 
    if (year) {
        this.current_year = parseInt(o.id.substr(o.id.indexOf('_') + 1));
        this.year_chooser.innerHTML = this.current_year; this.year_chooser.id = 'c' + o.id;
        this.years.parentNode.removeChild(this.years);
    } 
    this.cal_body.parentNode.removeChild(this.cal_body);
    this.initialize_calendar(); 
    this.build_calendar_body();
}; 

this.toggle_months = function() {
if (!this.month_wraper.getElementsByTagName('UL')[0]) {
this.months = document.createElement('UL'); this.months.id = 'months'; for (var i = 0; i < 12; i++) {
var month = document.createElement('LI');
month.id = 'm_' + i; month.innerHTML = the_months[i];
(i == this.current_month) ? month.style.color = '#ff0000' : ""; 
month.onclick = this.rebuild_calendar_body.bind(this, month, true, false);
this.months.appendChild(month);
} this.month_wraper.appendChild(this.months);
} else {
this.month_wraper.removeChild(this.month_wraper.getElementsByTagName('UL')[0]);
} if (this.year_wraper.getElementsByTagName('UL')[0]) {
this.year_wraper.removeChild(this.year_wraper.getElementsByTagName('UL')[0]);
}
};
this.toggle_years = function() {
if (!this.year_wraper.getElementsByTagName('UL')[0]) {
this.years = document.createElement('UL'); this.years.id = 'years';
this.minus = document.createElement('LI'); this.minus.innerHTML = '&nbsp;-&nbsp;';
this.minus.onmouseover = this.decrease_years.bind(this); this.minus.onmouseout = function() {
clearInterval(obj.d_int);
}; this.years.appendChild(this.minus);
for (var i = (parseInt(this.current_year) - 5); i < (parseInt(this.current_year) + 5); i++) {
var year = document.createElement('LI'); year.id = 'y_' + i; year.innerHTML = i; (i == this.current_year) ? year.style.color = '#ff0000' : ""; 
year.onclick = this.rebuild_calendar_body.bind(this, year, false, true); this.years.appendChild(year);
} this.plus = document.createElement('LI'); this.plus.innerHTML = '&nbsp;+&nbsp;'; this.plus.onmouseover = this.increase_years.bind(this); 
this.plus.onmouseout = function() { clearInterval(obj.i_int); }; 
this.years.appendChild(this.plus); this.year_wraper.appendChild(this.years);
} else { this.year_wraper.removeChild(this.year_wraper.getElementsByTagName('UL')[0]); } if (this.month_wraper.getElementsByTagName('UL')[0]) { 
this.month_wraper.removeChild(this.month_wraper.getElementsByTagName('UL')[0]); }
}; this.increase_years = function() {
var lis = this.years.getElementsByTagName('LI'); for (var i = 1; i < lis.length - 1; i++) {
lis[i].innerHTML = parseInt(lis[i].innerHTML) + 1; lis[i].id = 'y_' + lis[i].innerHTML;
(parseInt(lis[i].innerHTML) == this.current_year) ? lis[i].style.color = '#ff0000' : lis[i].style.color = '#000000';
} this.i_int = setTimeout(function() { obj.increase_years() }, 200);
};
this.decrease_years = function() {
var lis = this.years.getElementsByTagName('LI'); for (var i = 1; i < lis.length - 1; i++) {
lis[i].innerHTML = parseInt(lis[i].innerHTML) - 1;
lis[i].id = 'y_' + lis[i].innerHTML; (parseInt(lis[i].innerHTML) == this.current_year) ? lis[i].style.color = '#ff0000' : lis[i].style.color = '#000000';
} 
this.d_int = setTimeout(function() { obj.decrease_years() }, 200);
};
this.doc_body = document.body; this.cal_tbl = document.createElement('TABLE'); 
this.cal_tbl.style.position = 'absolute'; this.cal_tbl.style.backgroundColor = '#ffffff'; this.cal_tbl.id = 'calendar';
this.cal_head = document.createElement('THEAD'); this.cal_head_row = document.createElement('TR'); 
this.cal_head_cell = document.createElement('TD'); this.cal_head_cell.setAttribute('colSpan', '7');
this.month_wraper = document.createElement('DIV'); this.month_wraper.id = 'month_wraper'; 
this.month_chooser = document.createElement('DIV'); this.month_chooser.className = 'month_chooser';
this.month_chooser.id = 'cm_' + this.current_month;
this.month_chooser.innerHTML = the_months[this.current_month]; 
this.month_chooser.onclick = this.toggle_months.bind(this);
this.month_wraper.appendChild(this.month_chooser);
this.cal_head_cell.appendChild(this.month_wraper); this.year_wraper = document.createElement('DIV'); 
this.year_wraper.id = 'year_wraper';
this.year_chooser = document.createElement('DIV'); this.year_chooser.className = 'year_chooser'; 
this.year_chooser.id = 'cy_' + this.current_year; this.year_chooser.innerHTML = this.current_year;
this.year_chooser.onclick = this.toggle_years.bind(this); this.year_wraper.appendChild(this.year_chooser); 
this.cal_head_cell.appendChild(this.year_wraper); this.cal_head_row.appendChild(this.cal_head_cell);
this.cal_head.appendChild(this.cal_head_row); this.week_days = document.createElement('TR'); 
for (var i = 0; i < 7; i++) {
this.week_day = document.createElement('TD'); 
this.week_day.innerHTML = the_days[i];
this.week_days.appendChild(this.week_day);
} this.cal_head.appendChild(this.week_days); this.cal_tbl.appendChild(this.cal_head); 
this.cal_tbl.className = 'calendar'; this.cal_tbl.setAttribute('border', '1');
this.cal_tbl.style.left = get_left_pos(this.box) + 'px'; this.cal_tbl.style.top = get_top_pos(this.box) + 'px'; 
this.doc_body.appendChild(this.cal_tbl); this.build_calendar_body = function() {
this.cal_body = document.createElement('TBODY');
var counter = 1; for (var i = 0; i < this.needed_rows; i++) {
this.week_row = document.createElement('TR'); for (var j = 0; j < 7; j++) {
this.week_day = document.createElement('TD');
if (!i && (j < this.first_day_index) || (counter > this.length_of_current_month)) {
this.week_day.innerHTML = ''; 
} else {
(counter == this.current_day) ? this.week_day.style.fontWeight = 'bold' : "";
this.week_day.innerHTML = counter++; 
var this_date = this.current_year + (((this.current_month + 1) < 10) ? '0' + (this.current_month + 1) : (this.current_month + 1).toString()) + ((this.week_day.innerHTML < 10) ? '0' + this.week_day.innerHTML :
this.week_day.innerHTML).toString(); 
if ((this_date < this.beginning_date) || (this_date > this.ending_date)) {
this.week_day.style.color = '#cccccc'; 
} else {
this.week_day.style.cursor = 'pointer';
this.week_day.onclick = this.deinitialize_calendar.bind(this, (counter - 1), true);
} 
} this.week_row.appendChild(this.week_day);
} this.cal_body.appendChild(this.week_row);
} this.cal_tbl.appendChild(this.cal_body);
};
this.deinitialize_calendar = function(day, flag) {
    if (flag) {
        this.box.focus(); 
    if ((date_format == 'd-m-y') || (date_format == 'd.m.y') || (date_format == 'd/m/y')){
        this.box.value = ((day < 10) ? '0' + day : day).toString() + '.' + (((this.current_month + 1) < 10) ? '0' + (this.current_month + 1) : (this.current_month + 1).toString()) + '.' + this.current_year;
    } else if ((date_format == 'y-m-d') || (date_format == 'y.m.d') || (date_format == 'y/m/d')) {
        this.box.value = this.current_year + '.' + (((this.current_month + 1) < 10) ? '.' + (this.current_month + 1) : (this.current_month + 1).toString()) + '.' + ((day < 10) ? '0' + day : day).toString();
    }
    this.box.blur();
    } this.destroy();
};

this.destroy = function() {
    this.cal_tbl.parentNode.removeChild(this.cal_tbl);
    document.onclick = null;
    obj = null;
};
this.catch_click = function(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) targ = targ.parentNode;
    var parent = targ;
    while (parent) {
        parent = parent.parentNode;
        if (parent == this.cal_tbl) {
            return;
        }
    } 
    if (this.flag) {
        this.destroy();
    } this.flag = true;
}; 
this.initialize_calendar();
    this.build_calendar_body();
    document.onclick = this.catch_click.bind(this); 
    return true;
};

Date.prototype.format = function(mask) {
    var date = mask.replace(/y/, this.getFullYear()).replace(/m/, ((this.getMonth() + 1) < 10) ? '0' + (this.getMonth() + 1) : (this.getMonth() + 1)).replace(/d/, (this.getDate() < 10) ? '0' + this.getDate() : this.getDate()).replace(/h/, (this.getHours() < 10) ? '0' + this.getHours() : this.getHours()).replace(/i/, (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes()).replace(/s/, (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds());
    return date;
}

Function.prototype.bind = function(object) {
    var method = this;
    var old_arguments = to_array(arguments).slice(1);
    return function() {
    var new_arguments = to_array(arguments);
    return method.apply(object, old_arguments.concat(new_arguments));
    };
}

Function.prototype.bind_event_listener = function(object) {
    var method = this;
    var old_arguments = to_array(arguments).slice(1);
    return function(event) {
    return method.apply(object, event || window.event, old_arguments);
    };
}

Array.prototype.in_array = function(obj) {
    var len = this.length;
    for (var i = 0; i <= len; i++) {
        if (this[i] == obj) return true;
    } return false;
}

Array.prototype.index_array = function(obj) {
    var len = this.length;
    for (var i = 0; i <= len; i++) {
        if (this[i] == obj) return i;
    } 
}
function to_array(pseudo_array) {
    var result = [];
    for (var i = 0; i < pseudo_array.length; i++) result.push(pseudo_array[i]);
    return result;
}

function get_top_pos(elm) {
    var value = elm.offsetTop + elm.offsetHeight;
    while ((elm = elm.offsetParent) != null) value += elm.offsetTop;
    return value + 0;
}

function get_left_pos(elm) {
    var value = elm.offsetLeft;
    while ((elm = elm.offsetParent) != null) value += elm.offsetLeft;
    return value + 0;
}

function confirm_action(url) {
    if (confirm("Click OK to delete selected item!")) {
        window.location.href = url.replace(/&amp;/gi, "&");
    }
}

var price = { "0":"", "1": "66,00", "2": "98,00", "3": "32,00", "4": "60,00", "5": "68,00" };

var error = {
    "hr" : [
        "Sva polja su obavezna",
        "E-mail nije unešen u ispravnom formatu",
        "Oznaka jezika je obavezna, i sukladno ISO standardu mora biti duljine 2 abecedna znaka",
        "Naziv jezika je obavezan i ne moze sadržavati nista osim abecednih znakova",
        "Datoteka jezičnik konstanti ne moze biti prazna",
        "Nije unešen naziv oglasivača",
        "Nije unešen naziv medija",
        "Zbog sigurnosnih razloga:\n- lozinka ne može sadržavati specijalne i dijakritičke znakove\n- mora sadržavati najmanje jedno malo ili veliko slovo\n- najmanje jedan broj i\n- mora biti duljine 6 do 15 znakova!",
        "Nije unešeno korisničko ime (odnosno e-mail) ili pak nije u ispravnom formatu",
        "Nije unešen naziv kategorije",
        "Nije izabrana niti jedna (pod)kategorija",
        "Nije unešen naslov oglasa",
        "Nije izabran oglasivač",
        "Oglas mora imati opis ili pak ključne riječi",
        "Nije unešen datum",
        "Nije unešena cijena ili je pak unešena u krivom formatu",
        "Inačici oglasa nije dodana niti jedna datoteka",
        "Naziv datoteke sadržava nedozvoljene znakove!\n\nNaziv datoteke može sadržavati samo:\n- mala i velika slova engleske abecede\n- brojeve, donju crtu [_] ili znak minus [-]\n\nTočka se može nalaziti samo:\n- u ulozi razdjelnika samoga naziva i ekstenzije datoteke",
        "Nije izabran medij",
        "Nisu unešene ključne rijeći",
        "Nije izabran niti jedan medij"
       ],
    "en" : [
        "All fields are required",
        "E-mail nije unesen u ispravnom formatu",
        "Oznaka jezika je obavezna, i sukladno ISO standardu mora biti duljine 2 abecedna znaka",
        "Naziv jezika je obavezan i ne moze sadrzavati nista osim abecednih znakova",
        "Datoteka jezicnik konstanti ne moze biti prazna",
        "Nije unesen naziv oglasivaca",
        "Nije unesen naziv medija",
        "Zbog sigurnosnih razloga:\n- lozinka ne moze sadrzavati specijalne i dijakriticke znakove\n- mora sadrzavati najmanje jedno malo ili veliko slovo\n- najmanje jedan broj i\n- mora biti duljine 6 do 15 znakova!",
        "Nije uneseno korisnicko ime (odnosno e-mail) ili pak nije u ispravnom formatu",
        "Nije unesen naziv kategorije",
        "Nije izabrana niti jedna (pod)kategorija",
        "Nije unesen naslov oglasa",
        "Nije izabran oglasivac",
        "Oglas mora imati opis ili pak kljucne rijeci",
        "Nije unesen datum",
        "Nije unesena cijena ili je pak unesena u krivom formatu",
        "Inacici oglasa nije dodana niti jedna datoteka",
        "Naziv datoteke sadržava nedozvoljene znakove!\n\nNaziv datoteke može sadržavati samo:\n- mala i velika slova engleske abecede\n- brojeve, donju crtu [_] ili znak minus [-]\n\nTočka se može nalaziti samo:\n- u ulozi razdjelnika samoga naziva i ekstenzije datoteke",
        "Nije izabran medij",
        "What about keywords?",
        "What about media types?"
    ]
};

function validator(obj, lang) {
    var flag = true;
    switch (obj.id) {
        case "contact-form":
            if (obj.company_or_name.value.length <= 0 || obj.e_mail.value.length <= 0 || obj.message.value.length <= 0) {
                flag = false;
                msg = error[lang][0].toString();
                break;
            }
            var pattern = new RegExp("^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$");
            if ((obj.e_mail.value.length <= 0) || !pattern.test(obj.e_mail.value)) {
                flag = false;
                msg = error[lang][1].toString();
                break;
            }
            break;
        case "language-form":
            var pattern = new RegExp("^[a-z]{2}$");
            if ((obj.language_code.value.length <= 0) || !pattern.test(obj.language_code.value)) {
                flag = false;
                msg = error[lang][2].toString();
                break;
            }        
            var pattern = new RegExp("^[a-zA-Z]+$");
            if ((obj.language_name.value.length <= 0) || !pattern.test(obj.language_name.value)) {
                flag = false;
                msg = error[lang][3].toString();
                break;
            }
            if (obj.language_file.value.length <= 0) {
                flag = false;
                msg = error[lang][4].toString();
                break;
            }
            break;
        case "advertiser-form":
            if (obj.advertiser_name.value.length <= 0) {
                flag = false;
                msg = error[lang][5].toString();
                break;
            }
            break;
        case "media-form":
            if (document.getElementById("media_name_" + lang).value.length <= 0) {
                flag = false;
                msg = error[lang][6].toString();
                break;
            }
            break;            
        case "profile-form":
            var pattern = new RegExp("(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,15})$");
            if ((!obj.password.disabled) && (!pattern.test(obj.password.value))) {
                flag = false;
                msg = error[lang][7].toString();
                break;
            }
            break;
        case "user-form":
            var pattern = new RegExp("^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$");
            if ((obj.username.value.length <= 0) || !pattern.test(obj.username.value)) {
                flag = false;
                msg = error[lang][8].toString();
                break;
            }
            pattern = new RegExp("(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,15})$");
            if ((!obj.password.disabled) && (!pattern.test(obj.password.value))) {
                flag = false;
                msg = error[lang][7].toString();
                break;
            }
            break;
        case "category-form":
            if (document.getElementById("category_name_" + lang).value.length <= 0) {
                flag = false;
                msg = error[lang][9].toString(); ;
                break;
            }
            if (obj.parent_id.selectedIndex == -1) {
                flag = false;
                msg = error[lang][10].toString();
                break;
            }
            break;    
        case "ad-form":
            if (document.getElementById("ad_name_" + lang).value.length <= 0) {
                flag = false;
                msg = error[lang][11].toString();
                break;
            }
            if (obj.advertiser_id.selectedIndex == -1) {
                flag = false;
                msg = error[lang][12].toString();
                break;
            }
            if ((document.getElementById("ad_description_" + lang).value.length <= 0) &&  (document.getElementById("ad-form").keywords.value.length <= 0)){
                flag = false;
                msg = error[lang][13].toString();
                break;
            }
            break;
        case "blob-form":
            if (obj.first_appearance.value.length <= 0) {
                flag = false;
                msg = error[lang][14].toString();
                break;
            }
            if (!obj.media_id.selectedIndex) {
                flag = false;
                msg = error[lang][18].toString();
                break;
            }            
            var pattern = new RegExp("^\\d*[0-9](\.\\d*[0-9])?$");
            if (obj.blob_price.value.length <= 0 || !pattern.test(obj.blob_price.value)) {
                flag = false;
                msg = error[lang][15].toString();
                break;
            }
            if (obj.blob_id.value.length <= 0 && obj.blob_file.value.length <= 0) {
                flag = false;
                msg = error[lang][16].toString();
                break;
            }
            if (obj.blob_id.value.length <= 0 && !file_name_valid(obj.blob_file.value)) {
                flag = false;
                msg = error[lang][17].toString();
                break;
            }
            break;
        case "notifier-form":
            if (obj.keywords.value.length <= 0) {
                flag = false;
                msg = error[lang][19].toString();
                break;
            }
            var media = false;
            for (i = 0; i < obj.media.length; i++) {
                if (obj.media[i].checked) {
                    media = true;
                    break;
                }
            }
            if (!media) {
                flag = false;
                msg = error[lang][20].toString();
                break;
            }
            break;
    }
    
    if(flag){
        return true;
    }else{
        alert(msg);
        return false;    
    }
}


function file_name_valid(str) {

    var backslash = new RegExp("[\\\\]")
    var pattern = new RegExp("^[a-zA-Z0-9_\-]+\.[a-zA-Z0-9]{2,4}$");
    var tmp = ""; backslash_found = false;
    for (var i = str.length - 1; i >= 0; i--) {
        if (str.charAt(i).match(backslash)) {
            backslash_found = true;
            break;
        } else {
            tmp += str.charAt(i);
        }
    }

    if (navigator.appName.match(/[Microsoft]/)) {
        if (!pattern.test(tmp.reverse())) {
            return false;
        } else {
            return true;
        }
    } else {
        if (backslash_found || !pattern.test(tmp.reverse())) {
            return false;
        } else {
            return true;
        }
    }
}

String.prototype.reverse = function() { 
	return this.split("").reverse().join(""); 
}

function autoComplete(field, select, property, forcematch) {

    var found = false;
    for (var i = 0; i < select.options.length; i++) {
        if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
            found = true;
            break;
        }
    }

    if (found) {
        select.selectedIndex = i;
        update_keywords(select.options[select.selectedIndex].text);
    } else {
        select.selectedIndex = -1;
    }

    if (field.createTextRange) {
        if (forcematch && !found) {
            field.value = field.value.substring(0, field.value.length - 1);
            return;
        }
        var cursorKeys = "8;46;37;38;39;40;33;34;35;36;45;";
        if (cursorKeys.indexOf(event.keyCode + ";") == -1) {
            var r1 = field.createTextRange();
            var oldValue = r1.text;
            var newValue = found ? select.options[i][property] : oldValue;
            if (newValue != field.value) {
                field.value = newValue;
                var rNew = field.createTextRange();
                rNew.moveStart('character', oldValue.length);
                rNew.select();
            }
        }
    }
}

var advertiser = "";
function update_keywords(option) {
    var pattern = new RegExp(advertiser);
    var target = document.getElementById("ad-form").keywords;
    if (advertiser.length > 0 && pattern.test(target.value)) {
        target.value = target.value.replace(advertiser, option);
    } else {
        if (target.value.length <= 0) {
            target.value += option;
        } else {
            target.value += ", " + option;
        }
    }
    advertiser = option;
    //document.getElementById("ad-form").advertiser_name.value = option;
}

function jsScroller(o, w, h) {
    var self = this;
    var list = o.getElementsByTagName("div");
    for (var i = 0; i < list.length; i++) {
        if (list[i].className.indexOf("scroller-content") > -1) {
            o = list[i];
        }
    }

    this._setPos = function(x, y) {
        if (x < this.viewableWidth - this.totalWidth)
            x = this.viewableWidth - this.totalWidth;
        if (x > 0) x = 0;
        if (y < this.viewableHeight - this.totalHeight)
            y = this.viewableHeight - this.totalHeight;
        if (y > 0) y = 0;
        this._x = x;
        this._y = y;
        with (o.style) {
            left = this._x + "px";
            top = this._y + "px";
        }
    };

    this.reset = function() {
        this.content = o;
        this.totalHeight = o.offsetHeight;
        this.totalWidth = o.offsetWidth;
        this._x = 0;
        this._y = 0;
        with (o.style) {
            left = "0px";
            top = "0px";
        }
    };
    this.scrollBy = function(x, y) {
        this._setPos(this._x + x, this._y + y);
    };
    this.scrollTo = function(x, y) {
        this._setPos(-x, -y);
    };
    this.stopScroll = function() {
        if (this.scrollTimer) window.clearInterval(this.scrollTimer);
    };
    this.startScroll = function(x, y) {
        this.stopScroll();
        this.scrollTimer = window.setInterval(
			function() { self.scrollBy(x, y); }, 40
		);
    };
    this.swapContent = function(c, w, h) {
        o = c;
        var list = o.getElementsByTagName("div");
        for (var i = 0; i < list.length; i++) {
            if (list[i].className.indexOf("scroller-content") > -1) {
                o = list[i];
            }
        }
        if (w) this.viewableWidth = w;
        if (h) this.viewableHeight = h;
        this.reset();
    };

    this.content = o;
    this.viewableWidth = w;
    this.viewableHeight = h;
    this.totalWidth = o.offsetWidth;
    this.totalHeight = o.offsetHeight;
    this.scrollTimer = null;
    this.reset();
}

function init() {

    //alert("shit browser:" + navigator.appVersion);
    document.getElementById("content").className = (navigator.appVersion.match(/MSIE 6/)) ? "IE6" : "IEFF0SC";
    
    var el = document.getElementById("scroller") || null;
    if (el != null) {
        scroller = new jsScroller(el, 340, 248);
        var arrows = document.getElementById("arrows").getElementsByTagName("SPAN");
        if (document.getElementById("scroller").getElementsByTagName("P").length > 6) {
            for (var i = 0; i < arrows.length; i++) {
                arrows[i].style.visibility = "visible";
            }
        } else {
            for (var i = 0; i < arrows.length; i++) {
                arrows[i].style.visibility = "hidden";
            }        
        }
    }

    if (document.getElementById("ad-form") != null) {
        //alert("forma je tu");
        var target = document.getElementById("ad-form").advertiser_id;
        if (target.selectedIndex != -1) {
            advertiser = target.options[target.selectedIndex].text;
            //alert("...i nije prazna:" + advertiser);
        }
    }

    // floating banner on the right side
    var x_of_outer = get_left_pos(document.getElementById('wraper'));
    var banner = document.getElementById('banner');
    banner.style.left = x_of_outer + 980 + 20 + 'px';	 	

}

window.onload = function() { init(); };

