// JavaScript Document
function addToLinked(base64json, DEFAULT_SITE_FILES_FOLDER){

  var filedata=new Object(JSON.parse(Base64.decode(base64json)));
  
  var nominalsize = Base64.encode('<img src="'+filedata.filename+'" />');
  
  var medsizname = returnImgPath(filedata.id, filedata.fileext, 'medsiz_', DEFAULT_SITE_FILES_FOLDER);
  var medsizWithLink = Base64.encode('<a href="'+filedata.filename+'" class="fancy" title="'+filedata.comment+'"><img src="'+medsizname+'" /></a>');
  
  var thumbname = returnImgPath(filedata.id, filedata.fileext, 'tmb_', DEFAULT_SITE_FILES_FOLDER);
  var thumbWithLink = Base64.encode('<a href="'+filedata.filename+'" class="fancy" title="'+filedata.comment+'"><img src="'+thumbname+'" /></a>');

  string='<li id="linked_item'+filedata.id+'">'
					+'<table width="100%">'
							+'<tr>'
								+'<td width="1%" nowrap="nowrap">'+filedata.id+'. </td>'
            		+'<td><a class="fancy" href="'+filedata.filename+'" target="_blank">'+filedata.name+'.'+filedata.fileext+' | <img src="'+thumbname+'" /></a></td>'
            		+'<td width="120">'
            		  +'<img src="../images/rte/leftalignimage.gif" alt="Unesi veliku sliku" onclick="InsStringIntoTextarea(\'text\',\''+nominalsize+'\')" style="cursor:pointer" /> | '
            			+'<img src="../images/rte/leftalignmedsiz.gif" alt="Unesi srednju sliku" onclick="InsStringIntoTextarea(\'text\',\''+medsizWithLink+'\')" style="cursor:pointer"/> | '
            			+'<img src="../images/rte/leftalignthumb.gif" alt="Unesi thumb" onclick="InsStringIntoTextarea(\'text\',\''+thumbWithLink+'\')" style="cursor:pointer"/>'
                +'</td>'
            		+'<td width="1%">'
            			+'<div class="remove_button" onclick="$(\'#linked_item'+filedata.id+'\').remove();">&nbsp;</div>'
            			+'<input type="hidden" name="files[]" value="'+filedata.id+'"/>'
          			+'</td>'
            	+'</tr>'
          +'</table>'
         +'</li>';
  $('#lista').append(string);
  initFancyBox();
}

function returnImgPath(id, ext, preff, DEFAULT_SITE_FILES_FOLDER){
  name=str_pad(id, 6, "0", 'STR_PAD_LEFT');
  path="/"+DEFAULT_SITE_FILES_FOLDER+"/"+name+"/"+preff+name+"."+ext;
  return path;
}

function str_pad (input, pad_length, pad_string, pad_type) {
    // Returns input string padded on the left or right to specified length with pad_string 
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/str_pad
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://getsprink.com)
    // +      input by: Marco van Oort
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'
    
    var half = '', pad_to_go;
 
    var str_pad_repeater = function (s, len) {
        var collect = '', i;
 
        while (collect.length < len) {collect += s;}
        collect = collect.substr(0,len);
 
        return collect;
    };
 
    input += '';
    pad_string = pad_string !== undefined ? pad_string : ' ';
     
    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }
        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    }
 
    return input;
}


function initFancyBox(){
  $("a.fancy").fancybox({
      'zoomOpacity' : true,
      'overlayShow' : true,
      'overlayOpacity' : 0.7,
      'zoomSpeedIn' : 500,
      'zoomSpeedOut' : 500,
      'hideOnContentClick' : false
  });
}

function InsStringIntoTextarea (idfield, str){
  var str_act=Base64.decode(str);
  if($('#'+idfield).css('display')=='none'){
    $('iframe').contents().find('body').append(str_act);
  } else {
    var oldval=$('#'+idfield).val();
    var newval=str_act+oldval;
    $('#'+idfield).val(newval);
  }
}

function drawSWF(_where, _moviepath, _width, _height){
  var s1 = new SWFObject(_moviepath, "mymovie" ,_width, _height, "10");
    s1.addParam("wmode", "transparent");
	  s1.write(_where);
}

function insertSelectedTextsIntoIssue(){
  $('.nonpublishedtext:checked').each(function(){
    var type_textid=$(this).val().split('_');
    var t=type_textid[0];
    var v=type_textid[1];
    
    var oldamount=$("#ol_for_type_"+t+" > li").length;
    
    var type_weight=Number($("#weight_for_type_"+t).val());
    
    var title=$("#label"+v).html();
    
    var newhtml='<li id="li_for_'+t+'_'+v+'">';
    newhtml+='<input type="hidden" name="weight[]" value="'+oldamount+'" id="prepaired_weight_'+t+'_'+v+'" class="prepairedforpublishing_weight" />';
    newhtml+='<input type="checkbox" name="eraser[]" value="'+v+'" checked="checked" id="prepaired_'+t+'_'+v+'" class="prepairedforpublishing" />';
    newhtml+='<input type="hidden" name="id_text[]" value="'+v+'"  />';
    newhtml+='<input type="hidden" name="type_weight[]" value="'+type_weight+'"  class="prepairedforpublishing_type_weight_'+t+'" />';
    newhtml+='<label for="prepaired_'+t+'_'+v+'" >'+title+'</label>';
    newhtml+='</li>';
    
    if (oldamount==0){
      $("#delimiter").before($("#li_for_type_"+t));
    }
    
    $("#ol_for_type_"+t).append(newhtml);
    
    var newamount=$("#ol_for_type_"+t+" > li").length;
    
    $("#li_for_type_"+t+" span.amount").html(String(newamount));
    
    $(this).removeAttr("checked");
    
    serializeTypeListu();
  });
}
function removeSelectedTextsFromIssue(){
  $('.prepairedforpublishing:checked').each(function(){
    var prep_type_textid=$(this).attr('id').split("_");

    var t=prep_type_textid[1];
    var v=prep_type_textid[2];
    
    $('#li_for_'+t+'_'+v).remove();
    var newamount=Number(Number($("#li_for_type_"+t+" span.amount").html())-1);
    $("#li_for_type_"+t+" span.amount").html(String(newamount));
  });
}

function serializeListu(){
    $('.ol_for_issue').each(function(){
      var thisid = $(this).attr('id');
      var lista=$("#"+thisid).sortable('toArray');
      if (lista.length>0){
        for (var k in lista){
          var divfor=lista[k].split('_');
          var wghtid="prepaired_weight_"+divfor[2]+"_"+divfor[3];
          $("#"+wghtid).val(k);
        }
      }
    });
  }
  function serializeTypeListu(){
      var lista=$("#new_issue_collection").sortable('toArray');
      if (lista.length>0){
        for (var k in lista){
          var olfor=lista[k].split('_');
          var wghtid="weight_for_type_"+olfor[3];
          $("#"+wghtid).val(k);
          $('.prepairedforpublishing_type_weight_'+olfor[3]).val(k);
        }
      }
  }

function useFancyOnThis(path){
  
}

function insertCommentForText(id){
  var author = $('#comment_author').val();
  var comment = $('#comment').val();
  if (author!='' && comment!=''){
    $.ajax({
     type: "POST",
     url: "/getjson.php",
     dataType:"json",
     data: "action=insertComment&author="+author+"&comment="+comment+"&id="+id,
     success: function(msg){
      var message="Vaš komentar je unešen";
      $('#comment_author').val('');
      $('#comment').val('');
      $('#add_comment').slideToggle();
      if (!msg) {
        message="Došlo je do greške, molimo pokušajte ponovo";
      }
      alert(message);
     }
   });
  } else {
    alert ('Potrebno je popuniti sva polja. Hvala');
  }
}
function alowComment(id){
  var verify=0;
  if ($("#verify_"+id+":checked").val()!=null){
    verify = 1;
  }
  if (id!=0 && id!=null){
    $.ajax({
     type: "POST",
     url: "/getjson.php",
     dataType:"json",
     data: "action=alowComment&id="+id+"&verify="+verify,
     success: function(msg){
      var message="Ovaj komentar je dozvoljen";
      if (!msg) {
        message="Došlo je do greške, molimo pokušajte ponovo";
      }
      alert(message);
      $(document).refresh();
     }
   });
  }
}

function toggleChecked(master_id, classname){
  if ($('#'+master_id).attr('checked')){
    $('.'+classname).attr('checked','checked')
  } else {
    $('.'+classname).removeAttr('checked');
  }
}
function addSingleUserField(){
  var singlediv='<div style="background-color:#CCC;padding:10px; margin:10px;">'+$('.singleuser').html()+'</div>';
  $('#populus').append(singlediv);
}
function removeVox(vox_id){
  if(confirm('Da li ste sigurni?')){
    if (vox_id!=0 && vox_id!=null){
      $.ajax({
       type: "POST",
       url: "/getjson.php",
       dataType:"json",
       data: "action=deleteVox&id="+vox_id,
       success: function(msg){
        var message="Uklonjeni komentar i slika";
        if (!msg) {
          message="Došlo je do greške, molimo pokušajte ponovo";
        }
        alert(message);
        $(document).refresh();
       }
     });
    }
  }
}

function displayNewsList(divid){
  switch (divid){
    case 'latestnews':
      $('.othernewscontent').hide();
      $('#latestnews').show();
      $('.sel').removeClass('sel');
      $('#latestnewslink').addClass('sel');
    break;
    case 'mostreadnews':
      $('.othernewscontent').hide();
      $('#mostreadnews').show();
      $('.sel').removeClass('sel');
      $('#mostreadnewslink').addClass('sel');
    break;
    case 'mostcomentednews':
      $('.othernewscontent').hide();
      $('#mostcomentednews').show();
      $('.sel').removeClass('sel');
      $('#mostcomentednewslink').addClass('sel');
    break;
  }
}

function startListetningSearchAndArchive(){
  $(".searchformdiv #q").focus(function(){
    if ($(this).val()=='Pronađi') $(this).val('');
    $(".searchformdiv #q").addClass('focused');
  });
  $(".searchformdiv #q").blur(function(){
    if ($(this).val()=='') {
      $(this).val('Pronađi');
      $(".searchformdiv #q").removeClass('focused');
    }
  });
  
  $("#archive_date").focus(function(){
    if ($(this).val()=='Arhiva') $(this).val('');
    $("#archive_date").addClass('focused');
  });
  $("#archive_date").blur(function(){
    if ($(this).val()=='') {
      $(this).val('Arhiva');
      $("#archive_date").removeClass('focused');
    }
  });
}