
function _(string){
    var messages = {
    'Name':'Ime',
    'E-mail':'E-mail',
    'Please enter your email. Ex. john.smith@gmail.com':'Molimo unesite svoj e-mail. Npr. ivan.ivanov@gmail.com',
    'Message':'Komentar',
    'Please enter the words in the image':'Molimo unesite slova koja vidite na slici',
    'Please enter the word exactly as they appear in the image.':'Molimo unesite slova koja vidite na slici',
    'Post a comment':'Komentirajte',
    'You must fill in ALL of the fields.':'Morate ispuniti SVA polja',
    'Leave a comment':'Komentirajte',
    'Name must not be empty':'Polje "Ime" ne smije biti prazno',
    'Email must not be empty':'Polje "E-mail" ne smije biti prazno',
    'Please enter a valid email':'Molimo unesite ispravan e-mail',
    'Cancel':'Odustani',
    'Refresh':'Osvježi'
    };
    
    if( messages[string] && typeof messages[string] != 'undefined'){
        return messages[string]
    }

    return string
}

function $create(name){
    return document.createElement(name);
}

// Provide the XMLHttpRequest class for IE 5.x-6.x:
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
};

/* var RecaptchaStr_hr = {
    visual_challenge : "Get a visual challenge",
    audio_challenge : "Get an audio challenge",
    refresh_btn : "Get a new challenge",
    instructions_visual : "Type the two words:",
    instructions_audio : "Type what you hear:",
    help_btn : "Help",
    play_again : "Play sound again",
    cant_hear_this : "Download sound as MP3",
    incorrect_try_again : "Incorrect. Try again."
}; */

function validate_captcha(challenge, response){
   var req = new XMLHttpRequest();  
   req.open("POST", '/captcha/validate', false);  
   //// set headers and mime-type
   req.setRequestHeader("Content-Length", challenge.length+response.length);
   var body = "";
   var boundary = "proto" + Math.random();
   
   req.setRequestHeader("Content-Type", 'multipart/form-data; boundary='+boundary);
   body += "--" + boundary + "\n";
   body += 'Content-Disposition: form-data; name="challenge"\n';
   body += "\n";
   body += challenge + "";
   body += "\n";
   body += "--" + boundary + "\n";
   body += 'Content-Disposition: form-data; name="response"\n';
   body += "\n";
   body += response + "";
   body += "\n";
   body += "--" + boundary + "--";
   body += "\n";
   currentreq = req
   req.send(body)
   
   if(req.status != 200)
       return false;
   
   var result = req.responseText;
   
   var _result = null
   try {
       eval('_result = '+result);
   }
   catch(e){
       //console.error(e)
   }
   
   if(_result && _result.type == 'success'){
       return true
   }
   else if(_result && _result.type == 'failure'){
       alert(_result.data.message)
   }
   
   disable_submit();
}

function disable_submit(){
    if(curdisabled){
        curdisabled.removeAttribute('disabled')
    }
}

function submitTest(evt){

var buff

// process event here, handles both IE and Mozilla event models

evt = (evt) ? evt : ((window.event) ? window.event : "")

if (evt) {

elem = (evt.target) ? evt.target : evt.srcElement;

URLString = document.test.root.value + "xmlhttp.asp";

//alert(URLString);

 

http.open("POST", URLString, true);

http.onreadystatechange = processReqChange;

http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

http.send("action=submitTest");

}

}

function stop_event(e){
    if(!e) return;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = false;

	//e.stopPropagation works only in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
    return false
}

function getEventAndTarget(e){
    var event = e || window.event;
    var target = event.target || event.srcElement;
    
    return [event, target];
}

// Use: listen("event name", elem, func);
function listen(evnt, elem, func) {
    if (elem.attachEvent) { // IE DOM
        var r = elem.attachEvent("on"+evnt, func);
        return r;
    }
    else if (elem.addEventListener){// W3C DOM
        elem.addEventListener(evnt,func,false);
    }
    else{
        //window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
    }
}

function callbackFunction(ev, id){
  if (currentreq.readyState != 4)
    return;

  var result = currentreq.responseText;

  var _result = null
  try {
      eval('_result = '+result);
  }
  catch(e){
      //console.error(e)
  }
  
  if(_result && _result.type == 'success'){
    message = $create('div');
    message.className = 'xhrmessage';
    message.innerHTML = _result.data.message;
    alert(_result.data.message)
    delete_current_form();
  }
  else if(_result && _result.type == 'failure'){
    alert(_result.data.message);
    curdisabled.removeAttribute('disabled')
  }
  
  return stop_event(ev);
}

var currentreq = null;
var current_form = null;

function textarea_keypress(ev, id){
    var et = getEventAndTarget(ev);
    var event = et[0];
    var target = et[1];
    
    target.parentNode
    
    if(event.keyCode == 13 && event.ctrlKey){
        submit_comment_form(ev, id)
    }
}

var curdisabled = null;

function submit_comment_form(ev, id){
    var et = getEventAndTarget(ev);
    var event = et[0];
    var target = et[1];
    
    
    curdisabled = target;
    curdisabled.setAttribute('disabled','disabled')
    //console.log(event);
    
    var parent = target;
    while(parent.tagName != 'FORM'){
        parent = parent.parentNode;
    }
    
    currentform = parent;
    
    var url = parent.action
    // text value
    var value = parent.getElementsByTagName('textarea')[0].value;
    var inputs = parent.getElementsByTagName('input');
    var challenge = Captcha.get_challenge();
    var response = Captcha.get_response();
    
    if(inputs[0] && inputs[1]){
        var name = parent.getElementsByTagName('input')[0].value;
        var email = parent.getElementsByTagName('input')[1].value;
    }
    else {
        var name = '';
        var email = '';
    }
    
    if(value.length == 0){
        alert(replyformbuttonmessageer1);
        curdisabled.removeAttribute('disabled')
        return stop_event(ev);
    }
    else if(value.length < 4){
        alert(replyformbuttonmessageer2.replace('%s',4));
        curdisabled.removeAttribute('disabled')
        return stop_event(ev);
    }
    
    var req = new XMLHttpRequest();  
    req.open("POST", url, true);  
   //// set headers and mime-type appropriately  
   
   
    req.setRequestHeader("Content-Length", value.length+name.length+email.length+challenge.length);
    req.onreadystatechange = function(e){
        callbackFunction(e, id)
    };
    
    var body = "";
    var boundary = "proto" + Math.random();
    
    req.setRequestHeader("Content-Type", 'multipart/form-data; boundary='+boundary);
    body += "--" + boundary + "\n";
    body += 'Content-Disposition: form-data; name="body"\n';
    body += "\n";
    body += value + "";
    body += "\n";
    body += "--" + boundary + "\n";
    body += 'Content-Disposition: form-data; name="name"\n';
    body += "\n";
    body += name + "";
    body += "\n";
    body += "--" + boundary + "\n";
    body += 'Content-Disposition: form-data; name="email"\n';
    body += "\n";
    body += email + "";
    body += "\n";
    body += "--" + boundary + "\n";
    body += 'Content-Disposition: form-data; name="challenge"\n';
    body += "\n";
    body += challenge + "";
    body += "\n";
    body += "--" + boundary + "\n";
    body += 'Content-Disposition: form-data; name="response"\n';
    body += "\n";
    body += response + "";
    body += "\n";
    body += "--" + boundary + "--";
    body += "\n";
    currentreq = req
    req.send(body);
    
    
    return stop_event(event);
}

function show_reply_form(el,id){
    if(el.parentNode.parentNode.parentNode.lastChild.tagName == 'FORM'){
        return
    }
    
    var button = $create('button')
    button.innerHTML = replyformbuttonmessage
    button.onclick = submit_comment_form
    
    var textarea = $create('textarea')
    textarea.className = 'comment-message'
    listen('keyup', textarea, function(e){ textarea_keypress(e, id) });
    
    var _textarea = $create('div')
    _textarea.className = 'hbox'
    _textarea.appendChild(textarea)
    
    var form = $create('form')
    form.className = 'comment-form'
    form.action = '/articles/reply-comment?id='+id
    form.appendChild(_textarea)
    form.appendChild(button)
    
    el.parentNode.parentNode.parentNode.appendChild(form)
    
    delete_current_form = function(){
        if(!current_form)
            return;
        current_form.parentNode.removeChild(current_form)
        current_form = null;
        
    }    
    current_form = form;
}

function gen_comment_form(el,id,title){
    if(el.parentNode.lastChild.tagName == 'FORM'){
        return
    }
    var button = $create('button');
    button.innerHTML = replyformbuttonmessage
    //button.onclick = submit_comment_form
    listen('click', button, submit_comment_form);
    
    var textarea = $create('textarea');
    textarea.className = 'comment-message';
    listen('keyup', textarea, function(e){ textarea_keypress(e, null) } );
    
    var _textarea = $create('div')
    _textarea.className = 'hbox'
    _textarea.appendChild(textarea)
    
    var form = $create('form');
    form.className = 'comment-form'
    form.action = '/articles/'+id+'/comment';
    form.onsubmit = function(){return false;};
    form.appendChild(_textarea);
    form.appendChild(button);
    
    el.parentNode.appendChild(form);
    delete_current_form = function(){
        if(!current_form)
            return;
        current_form.parentNode.removeChild(current_form)
        current_form = null;
        
    }    
    current_form = form;
}

function row_labeled_input(label_str, input, helpstr){
    var label = $create('label');
        label.innerHTML = label_str;
        
    
    
    var cell_label = $create('td');
        cell_label.style.width='20%'
        cell_label.appendChild(label);
        
    var cell_input = $create('td');
        cell_input.appendChild(input);
        
    var row = $create('tr');
    
    if(helpstr){
        var help = $create('div');
            help.className ='help';
            help.innerHTML = helpstr;
        cell_input.appendChild(help)
    }
    
    row.appendChild(cell_label);
    row.appendChild(cell_input);
        
    return row;
}

function gen_anonymous_comment_form(el, id, title){
    var table = null, row = null, cell= null, label = null, input = null, box = null;
    
    if(el.parentNode.lastChild.tagName == 'FORM'){
        return
    }
    
    if(current_form){
        delete_current_form();
    }
    
    if(current_button){
        current_button.parentNode.removeChild(current_button)
        current_button = null;
    }
    
    var input_name = $create('input');
        input_name.type = 'text';
        input_name.tabindex = '-1';
        
    var input_email = $create('input');
        input_email.type = 'text';
        input_email.tabindex = '0';
        
    
    var textarea = $create('textarea');
        textarea.className = 'comment-message';
        textarea.tabindex = '1';
    listen('keyup', textarea, function(e){ textarea_keypress(e, null) } );
    
    
    var f1 = new LiveValidation(input_name);
    f1.add( Validate.Presence, { failureMessage: _("Name must not be empty") } );
    
    var f21 = new LiveValidation(input_email);
    f21.add( Validate.Presence, { failureMessage: _("Email must not be empty") } );
    f21.add( Validate.Email, { failureMessage: _("Please enter a valid email") } );
    
    var f21 = new LiveValidation(textarea);
    f21.add( Validate.Presence, { failureMessage: " " } );
    f21.add( Validate.Length, { minimum: 4, failureMessage: ' ', wrongLengthMessage: " ", tooShortMessage:' ', tooLongMessage:' ' } );
        
    var box_captcha = $create('div');
        
    tbody = $create('tbody');
    tbody.appendChild(row_labeled_input(_('Name'), input_name));
    tbody.appendChild(row_labeled_input(_('E-mail'), input_email, _('Please enter your email. Ex. john.smith@gmail.com')));
    tbody.appendChild(row_labeled_input(_('Message'), textarea));
    tbody.appendChild(row_labeled_input(_(' '), box_captcha, _('Please enter the word exactly as they appear in the image.')));
    
    table = $create('table');
    table.className = 'ui-form-layout-horizontal';
    table.appendChild(tbody)
    
    var button = $create('button');
        button.className = 'button-large submitBtn';
        button.innerHTML = '<span>'+replyformbuttonmessage+'</span>';
        listen('click', button, function(ev, id){
            button.disabled = true;
            var c = validate_captcha(Captcha.get_challenge(), Captcha.get_response())
            if(!c){
                return false;
            }
            submit_comment_form(ev, id)
            button.disabled = false;
        });
    
    var cancel_button = $create('button');
        cancel_button.className = 'negative';
        cancel_button.innerHTML = 'Cancel';
        listen('click', cancel_button, function(ev, id){
            var button = $create('button');
            button.innerHTML = 'Leave a comment'
            button.onclick = function(){
                var el = document.getElementById('article-commentary')
                gen_anonymous_comment_form(el, article_id, _("Post a comment"))
            }
            current_button = button;
            
            current_form.parentNode.replaceChild(button, current_form);
            current_form  = null;
        });
    
    var buttons = $create('div')
        buttons.className = 'buttons';
        buttons.appendChild(cancel_button);
        buttons.appendChild(button);
        
        
    var form = $create('form');
        form.className = 'comment-form ui-content-box'
        form.action = '/articles/'+id+'/comment?type=anonymous';
        form.onsubmit = function(){return false;};
    
    var notification = $create('div')
        notification.id = "information";
        notification.innerHTML = _('You must fill in ALL of the fields.')
        
        
    Captcha.generate(box_captcha);
    
    var frag = document.createDocumentFragment()
    //frag.appendChild(notification);
    frag.appendChild(table);
    frag.appendChild(buttons);
    
    form.appendChild(frag)
    
    el.parentNode.appendChild(form)
    
    //Recaptcha.create("6LerVQsAAAAAAAfeMf01gIB6BtxeAZHbflj6YE_h ",
    //box_captcha, {
    //   theme: "clean",
    //   lang: 'hr',
    //   custom_translations: RecaptchaStr_hr,
    //   tabindex:4,
    //   callback: null//Recaptcha.focus_response_field
    //});
    
    
    delete_current_form = function(){
        
        var button = $create('button');
        button.innerHTML = _('Leave a comment')
        button.onclick = function(){
            var el = document.getElementById('article-commentary')
            gen_anonymous_comment_form(el, article_id, _("Post a comment"))
        }
        current_button = button;
        
        if(!current_form)
            return;
        current_form.parentNode.replaceChild(button, current_form);
        current_form  = null;
        
    }
    
    current_form = form;
    
    //input_name.focus();
}

var current_button = null;

function show_anonymous_reply_form(el, id, title){
    var table = null, row = null, cell= null, label = null, input = null, box = null;
    
    if(el.parentNode.parentNode.parentNode.tagName == 'FORM'){
        return
    }
    
    if(current_form){
        delete_current_form();
    }
    
    var input_name = $create('input');
        input_name.type = 'text';
    
    var input_email = $create('input');
        input_email.type = 'text';
    
    var textarea = $create('textarea');
        textarea.className = 'comment-message';
    listen('keyup', textarea, function(e){ textarea_keypress(e, null) } );
        
    var box_captcha = $create('div');
        
    tbody = $create('tbody')
    tbody.appendChild(row_labeled_input(_('Name'), input_name));
    tbody.appendChild(row_labeled_input(_('E-mail'), input_email));
    tbody.appendChild(row_labeled_input(_('Message'), textarea));
    tbody.appendChild(row_labeled_input(' ', box_captcha, _('Please enter the word exactly as they appear in the image.')));
    
    table = $create('table');
    table.className = 'ui-form-layout-horizontal';
    table.appendChild(tbody)
    
    var f1 = new LiveValidation(input_name);
    f1.add( Validate.Presence, { failureMessage: _("Name must not be empty") } );
    
    var f21 = new LiveValidation(input_email);
    f21.add( Validate.Presence, { failureMessage: _("Email must not be empty") } );
    f21.add( Validate.Email, { failureMessage: _("Please enter a valid email") } );
    
    var f21 = new LiveValidation(textarea);
    f21.add( Validate.Presence, { failureMessage: " " } );
    f21.add( Validate.Length, { minimum: 4, wrongLengthMessage: " ", tooShortMessage:' ', tooLongMessage:' ' } );
    
    var button = $create('a');
        button.className = 'button-large submitBtn';
        button.innerHTML = '<span>'+replyformbuttonmessage+'</span>'
        listen('click', button, function(ev, id){
            button.disabled = true;
            var c = validate_captcha(Captcha.get_challenge(), Captcha.get_response())
            if(!c){
                return false;
            }
            submit_comment_form(ev, id)
            button.disabled = false;
        });
        
    var cancel_button = $create('button');
        cancel_button.className = 'negative';
        cancel_button.innerHTML = _('Cancel');
        listen('click', cancel_button, function(ev, id){
            current_form.parentNode.removeChild(current_form)
            current_form = null;
        });
    
    var buttons = $create('div')
        buttons.className = 'buttons';
        buttons.appendChild(cancel_button);
        buttons.appendChild(button);
        
        
    var form = $create('form');
        form.className = 'comment-form ui-content-box'
        form.action = '/articles/reply-comment?type=anonymous&id='+id;
        form.onsubmit = function(){return false;};
    
    
    var notification = $create('div')
        notification.id = "information";
        notification.innerHTML = _('You must fill in ALL of the fields.')
    
        
    //form.appendChild(notification);
    form.appendChild(table);
    form.appendChild(buttons);
    
    
    el.parentNode.parentNode.parentNode.appendChild(form)
    
    /* Recaptcha.create("6LerVQsAAAAAAAfeMf01gIB6BtxeAZHbflj6YE_h ",
    box_captcha, {
       theme: "clean",
       lang: 'hr',
       custom_translations: RecaptchaStr_hr,
       tabindex:4,
       callback: null
    }); */
    
    Captcha.generate(box_captcha)

    
    //input_name.focus();
    delete_current_form = function(){
        if(!current_form)
            return;
        current_form.parentNode.removeChild(current_form)
        current_form = null;
        
    }    
    current_form = form;
}

var delete_current_form = function(){

}
