/* part of fxisCMS framework */

$(document).ready(function(){

  jQuery.expr[':'].regex = function(elem, index, match) {
      var matchParams = match[3].split(','),
          validLabels = /^(data|css):/,
          attr = {
              method: matchParams[0].match(validLabels) ? 
                          matchParams[0].split(':')[0] : 'attr',
              property: matchParams.shift().replace(validLabels,'')
          },
          regexFlags = 'ig',
          regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
      return regex.test(jQuery(elem)[attr.method](attr.property));
  }

  //date format examples
  if($('#dateFormatExample').length > 0){
    $('#dateFormatExample').change(function(){
      $('#fxiscmsDateformat').val($('#dateFormatExample').val());
    });
  }
  
  //delete guestbook message
  if($('#messageDeleteButton').length > 0){
    $('#messageDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u dit bericht wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=gastenboek&a3=delete&mid='+$(this).attr('value'));
      }
    });
  }
  
  //delete blog message
  if($('#blogDeleteButton').length > 0){
    $('#blogDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u deze blog wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=blogs&a3=delete&b='+$(this).attr('value'));
      }
    });
  } 
  
  //delete blogitem message
  if($('#blogitemDeleteButton').length > 0){
    $('#blogitemDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u dit blogitem wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=blogs&a3=showblog&a4=delete&b='+$.url.param('b')+'&bi='+$(this).attr('value'));
      }
    });
  }
  
  //delete agenda message
  if($('#agendaDeleteButton').length > 0){
    $('#agendaDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u deze agenda wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=agendas&a3=delete&b='+$(this).attr('value'));
      }
    });
  } 
  
  //delete agendaitem message
  if($('#agendaitemDeleteButton').length > 0){
    $('#agendaitemDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u dit agendaitem wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=agendas&a3=showagenda&a4=delete&b='+$.url.param('b')+'&bi='+$(this).attr('value'));
      }
    });
  }      
  
  //blogs messages rows
  if ($('#tableBlogs').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^blogsRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var blogid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=blogs&a3=showblog&b='+blogid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  };
  
  //linkblocks messages rows
  if ($('#tableFootlinkblocks').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^footlinkblockRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var linkblockid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=voetlinks&a3=edit&l='+linkblockid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  };    
  
  //users messages rows
  if ($('#tableUsers').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^usersRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var userid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=gebruikers&a2=edit&u='+userid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  };  
  
  //blogitems messages rows
  if ($('#tableBlogitems').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^blogitemsRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var blogitemid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=blogs&a3=showblog&a4=edit&b='+$.url.param('b')+'&bi='+blogitemid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  };
  
  //agendaitems messages rows
  if ($('#tableAgendaitems').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^agendaitemsRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var agendaitemid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=agendas&a3=showagenda&a4=edit&b='+$.url.param('b')+'&bi='+agendaitemid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  };            

  //guestbook messages rows
  if ($('#tableGuestbook').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^messagesRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var messageid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=gastenboek&a3=edit&mid='+messageid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  };

  //pagination
  if($('#pagination').length > 0){
    $('#pagination span').each(function(){
      $(this).click(function(){
        var id = $(this).attr('id');
        var idReg = /^pagination-([0-9]+)$/.exec(id);
        if(id[0]){
          //construct url
          var params = $.url.attr('query');
          var path = $.url.attr('path');
          if(!/\/$/.exec(path)) path = path+'/';
          if(params){
            params = params.replace(/page[0-9]+/i,'page'+idReg[1]);
          } else {
            params = 'page'+idReg[1];
          }
          if(!/page/.exec(params)){
            params = params+'&page'+idReg[1];
          }        
          $(location).attr('href',path+'?'+params);
        }
      });
    });
  }

  //sortable rows
  if ($('.sortableTable').length > 0){
    //move up or down
    $('.sortableTable a').click(function(){
      var aid = $(this).attr("id");
      var reg = /^linksButton-(up|down)-([0-9]+)$/;
      var result = reg.exec(aid);
      if(result[0]){
        tr = $('#linksRow-'+result[2]);
        trParent = $('select.parent',tr).val();
        //move up!
        if (result[1] == 'up'){
          //search for next existing row with same parent
          trPrev = tr.prev();
          trPrevParent = $('select.parent',trPrev).val();
          while(trPrev.length > 0){
            if(trPrevParent == trParent){
        			tr.insertBefore(trPrev);
              reOrderRows(); 
              positionChilds();
        			break;
        		}
        		//check next one
            trPrev = trPrev.prev();
            trPrevParent = $('select.parent',trPrev).val();        		
          }
        //move down!
        } else if (result[1] == 'down'){
          //search for next existing row with same parent
          trNext = tr.next();
          trNextParent = $('select.parent',trNext).val();
          while(trNext.length > 0){
            if(trNextParent == trParent){
        			tr.insertAfter(trNext);
        			reOrderRows(); 
        			positionChilds();
        			break;
        		}
        		//check next one
            trNext = trNext.next();
            trNextParent = $('select.parent',trNext).val();              		
          }
        } else {
           return false;
        }    
      }
    });
    
    //onchange of select parent elemnt
    $('.sortableTable td select.parent').change(function(){
      positionChilds();
    });
    
    //initial sort
    positionChilds();
    
  }

  //messages
  if($('.message').length > 0){
    $('.message').fadeIn('fast',
      function(){
        setTimeout(function() { $('.message').fadeOut('slow'); }, 5000);
      }
    );
  }

  //wysiwyg editor
  if ($('#contentFieldFull').length > 0){
    $('#contentFieldFull').ckeditor({
            height: '400px',
            language: 'nl', 
            uiColor: '#d6e3f7',
            toolbar :
              [
                ['NewPage','Preview','Source','Undo','Redo','Save'],
                ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Scayt'],
                ['Find','Replace','-','SelectAll','RemoveFormat'],
                ['Maximize'],
                '/',
                ['Bold','Italic','Strike','Underline','Subscript','Superscript','-','NumberedList','BulletedList','Outdent','Indent','Blockquote'],
                ['Link','Unlink'],
                ['Styles','Format'],
                ['Image','Table','HorizontalRule','SpecialChar']
              ]            
    });
  };
  
  if ($('#subjectEmail').length > 0){
    $('#subjectEmail #subjectEmailNew').click(function(){
      //find new id for this row
      var ids = new Array();
      $(':regex(id,^subjectEmail-[0-9]+)').each(function(){
        //extract id
        var idName = $(this).attr('id');
        var reg = /([0-9]+)$/i;
        ids[ids.length] = reg.exec(idName)[1];
      });
      var newid = (getMax(ids)+1);

      //insert
      $('#subjectEmail').append('<div id="subjectEmail-'+newid+'" class="even">'+
                                '<input size="40" type="text" value="" name="fxiscms_subjects['+newid+']">'+
                                '<input size="40" type="text" value="" name="fxiscms_emails['+newid+']">'+
                                '</div>');
      //reset classes
      var zebra = 0;
      $(':regex(id,^subjectEmail-[0-9]+)').each(function(){
        $(this).removeClass('odd even').addClass(zebra % 2 ? 'even' : 'odd');
        zebra += 1;
      });
    });
    
  };
  
  if ($('#tablePages').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^pagesRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var pageid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=pagina&a3=edit&p='+pageid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  };
  
  if ($('#tableContactforms').length > 0){
    //we have the Pages Table, select all rows
    $(':regex(id,^contactformsRow-[0-9]+)').each(function(){
      //extract id
      var idName = $(this).attr('id');
      var reg = /([0-9]+)$/i;
      var contactid = reg.exec(idName);
      var rowClass = $(this).attr('class');
      
      //create link
      $(this).click(function(){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=contactformulier&a3=edit&c='+contactid[1]);
      });
      $(this).css('cursor','pointer');
      $(this).hover(function(){
          $(this).attr('class','hover');
        }, function() {
          $(this).attr('class',rowClass);
        }
      );
    });
  }; 
  
  if($('#contactDeleteButton').length > 0){
    $('#contactDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u dit contactformulier wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=contactformulier&a3=delete&c='+$(this).attr('value'));
      }
    });
  }   

  if ($('#datePicker').length > 0){
    $("#datePickerInput").datepicker({ dateFormat: 'dd-mm-yy' });
    $("#datetypeAuto").change(function(){
      if(this.checked){ 
        $('#datePicker').hide("fast");
      }
    });
    $("#datetypeManual").change(function(){
      if(this.checked){ 
        $('#datePicker').show("fast");
      }
    });
    if($('#datetypeAuto').attr('checked')) {
      $('#datePicker').hide();
    }
    if($('#datetypeManual').attr('checked')) {
      $('#datePicker').show();
    }       
  };
  
  //page type switch
  if ($('#pageTypeRow').length > 0){
    function showContentRowEditor(){
      $('#dateRow').show();
      $('#dateVisibleRow').show();
      $('#contentRowEditor').show();
      $('#contentRowFile').hide();
      $('#taxonomyRow').show();
      $('#contentRowHTML').hide();
      $('#attachmentRow').show();
      reOrderFormRows();
    }
    function showContentRowHTML(animation){
      $('#dateRow').show();
      $('#dateVisibleRow').show();
      $('#contentRowHTML').show();   
      $('#contentRowEditor').hide();
      $('#contentRowFile').hide();
      $('#taxonomyRow').show();
      $('#attachmentRow').show();
      reOrderFormRows();
    }
    function showContentRowFile(animation){
      $('#contentRowFile').show();  
      $('#dateRow').hide();
      $('#dateVisibleRow').hide();
      $('#contentRowEditor').hide();
      $('#contentRowHTML').hide();
      $('#attachmentRow').hide();  
      $('#taxonomyRow').hide(); 
      reOrderFormRows();   
    }
    
    //on change
    $("#pageTypeEditor").change(
      function(){
        if(this.checked){
          showContentRowEditor();
        }
      }
    );
    $("#pageTypeHTML").change(
      function(){    
        if(this.checked){
          showContentRowHTML();
        }
      }
    );
    $("#pageTypeFile").change(
      function(){    
        if(this.checked){
          showContentRowFile();
        }
      }
    );
    
    //proper layout when document is loaded
    $('#contentRowFile').hide();
    $('#dateRow').hide();
    $('#dateVisibleRow').hide();
    $('#contentRowEditor').hide();
    $('#contentRowHTML').hide();
    $('#attachmentRow').hide();
    if($('#pageTypeEditor').attr('checked')) {
      showContentRowEditor();
    }
    if($('#pageTypeHTML').attr('checked')) {
      showContentRowHTML();
    }
    if($('#pageTypeFile').attr('checked')) {
      showContentRowFile();
    }       
  }
  
  //delete linkblock
  if($('#linkblockDeleteButton').length > 0){
    $('#linkblockDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u dit linkblok wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=voetlinks&&a3=delete&l='+$(this).attr('value'));
      }
    });
  }  
  
  //insert new input row on newlink click
  $('#newlink').click(function(){
    //get highest linkid
    var linkid = 0;
    $('#editLinksRow input').each(function(){
      linkid = $(this).attr('rel') > linkid ? $(this).attr('rel') : linkid;
    });
    linkid = parseInt(linkid)+1;
    $('#editLinksRow .right').append('<div class="manualLinkItem">Title: <input type=\text" rel="'+linkid+'" name="fxiscms_linksmanual['+linkid+'][title]" value="" size="20" /> URL: <input rel="'+linkid+'" type="text" name="fxiscms_linksmanual['+linkid+'][url]" value=""  size="40" /> <a href="#" onClick="delLink($(this));">verwijderen</a></div> ');
  }); 
  
  //link block type switch
  if ($('#linkblockTypeRow').length > 0){
    function showManual(){
      $('#editLinksRow').show();
      $('#selectBlog').hide();
      $('#maxBlogItems').hide();
      $('#maxTags').hide();
      $('#maxPages').hide();
      $('#selectPage').hide();
      reOrderFormRows();
    }
    function showBlog(){
      $('#editLinksRow').hide();
      $('#selectBlog').show();
      $('#maxBlogItems').show();
      $('#maxTags').hide();
      $('#maxPages').hide();
      $('#selectPage').hide();
      reOrderFormRows();
    }
    function showPages(){
      $('#editLinksRow').hide();
      $('#selectBlog').hide();
      $('#maxBlogItems').hide();
      $('#maxTags').hide();
      $('#maxPages').show();
      $('#selectPage').hide();    
      reOrderFormRows();
    }
    function showPage(){
      $('#editLinksRow').hide();
      $('#selectBlog').hide();
      $('#maxBlogItems').hide();
      $('#maxTags').hide();
      $('#maxPages').hide();
      $('#selectPage').show(); 
      reOrderFormRows();   
    }
    function showTags(){
      $('#editLinksRow').hide();
      $('#selectBlog').hide();
      $('#maxBlogItems').hide();
      $('#maxTags').show();
      $('#maxPages').hide();
      $('#selectPage').hide(); 
      reOrderFormRows();   
    }        
    
    //on change
    $("#blockTypeManual").change(function(){
        if(this.checked){
          showManual();
        }
      }
    );
    $("#blockTypeBlog").change(function(){
        if(this.checked){
          showBlog();
        }
      }
    );
    $("#blockTypePages").change(function(){
        if(this.checked){
          showPages();
        }
      }
    );
    $("#blockTypePage").change(function(){
        if(this.checked){
          showPage();
        }
      }
    );
    $("#blockTypeTags").change(function(){
        if(this.checked){
          showTags();
        }
      }
    );                
    
    //proper layout when document is loaded
    if($('#blockTypeManual').attr('checked')) {
      showManual();
    }
    if($('#blockTypeBlog').attr('checked')) {
      showBlog();
    }
    if($('#blockTypePages').attr('checked')) {
      showPages();
    }  
    if($('#blockTypePage').attr('checked')) {
      showPage();
    } 
    if($('#blockTypeTags').attr('checked')) {
      showTags();
    }              
  }  
  
  if($('#pageDeleteButton').length > 0){
    $('#pageDeleteButton').click(function(){
      var confirmed = confirm("Weet u zeker dat u deze pagina wilt verwijderen? Deze actie is niet meer ongedaan te maken.");
      if(confirmed){
        $(location).attr('href','/fxiscms/index.php?a1=inhoud&a2=pagina&a3=delete&p='+$(this).attr('value'));
      }
    });
  }
  
  //file upload script
  if ($('#uploadButton').length > 0){  
    renumberUploads();
    $(function(){  
      var btnUpload = $('#uploadButton');  
      var status = $('#uploadStatus');  
      new AjaxUpload(btnUpload, {  
        action: 'fileupload.php',  
        name: 'fxis_attachment',  
        onSubmit: function(file, ext){  
          if (! (ext && /^(jpg|png|jpeg|gif|zip|rar|pdf|doc|docx|xps|deb|apk)$/i.test(ext))){  
            status.text('Alleen gecomprimeerde afbeeldingen (png, jpg, gif), archief bestanden (rar, zip), documenten (doc, docx, pdf, xps) of speciale bestanden (deb, apk) toegestaan.');  
            return false;  
          }  
          status.text('Uploading...');  
        },  
        onComplete: function(file, response){  
          //reset status
          status.text('');
          //check response
          var reg = /^(success|error)\|([^|]+)(?:\|([^|]+))?(?:\|([^|]+))?(?:\|([^|]+))?$/i;
          var responseMatch = reg.exec(response);
          if(responseMatch[1] == "success"){
            var fileName = responseMatch[3];
            var fileID = responseMatch[2];
            var fileType = responseMatch[4];
            var attachmentHtml = responseMatch[5];
            var uploadItemContent = '';
            $('#uploadList').append(attachmentHtml);    
          } else if (responseMatch[1] == "error"){
            status.text(responseMatch[2]);  
          } 
          renumberUploads();              
        }  
      });  
    });
  };
  
  //move attachments down
  $('.moveAttachDown').click(function(){
    var attachid = $(this).attr('rel');
    var position = $('#fxis_attachment-'+attachid+' input.inputPosition').val();
    var newposition = position+1;
    var lastpos = $('.uploadItem:last input.inputPosition').val();
    if(newposition <= lastpos){
      //move element
      $('#fxis_attachment-'+attachid).next().after($('#fxis_attachment-'+attachid));
    }
    renumberUploads();
  });

  //move attachments up
  $('.moveAttachUp').click(function(){
    var attachid = $(this).attr('rel');
    var position = $('#fxis_attachment-'+attachid+' input.inputPosition').val();
    var newposition = position-1;
    var firstpos = $('.uploadItem:first input.inputPosition').val();
    if(newposition >= firstpos){
      //move element
      $('#fxis_attachment-'+attachid).prev().before($('#fxis_attachment-'+attachid));
    }
    renumberUploads();
  });  
  
  
  //settings
  if($('input[name=fxiscms_sitename]').length > 0){
    
    checkGAenabled();
    checkGBenabled();
    checkPCenabled()
    //settomgs: show google analytics settings if enabled
    $('input[name=fxiscms_ga_enabled]').click(function(){
      checkGAenabled();    
    });
    $('input[name=fxiscms_gb_enabled]').click(function(){
      checkGBenabled();    
    });  
    $('input[name=fxiscms_pc_enabled]').click(function(){
      checkPCenabled();    
    });      
  }
  
  //codemirror
  if($('#codemirror').length > 0){
    var editor = CodeMirror.fromTextArea('codemirror', {
      height: "400px",
      parserfile: ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js"],
      stylesheet: ["/css/codemirror/xmlcolors.css", "/css/codemirror/jscolors.css", "/css/codemirror/csscolors.css"],
      path: "/js/codemirror/",
      continuousScanning: 100,
      tabMode: 'spaces'
    });
  } 
  
  //add tag
  $('a#addtag').click(function(){
    $('input#fxiscms_taxonomy').val($('input#fxiscms_taxonomy').val()+','+trim($('select#fxiscms_alltags option:selected').text()));
  }); 
  
});

//function to delete a link from the footnote link manual select
function delLink(element){
  element.parent().remove();
}
  
function reOrderFormRows(){
  var zebra = 'odd';
  $('.fxiscmsform .row:visible').each(function(){
    zebra = zebra == 'odd' ? 'even' : 'odd';
    $(this).removeClass('odd','even');
    $(this).addClass(zebra);
  });
}

//attachment renumbering
function renumberUploads(){
  var num = 1;
  var blogitemimage = $('#fxiscms_blogitemimage').val();
  var blogitemimageSet = false;
  $('#blogitemimageText').remove();
  $('.uploadItem').each(function(){
    //add blogitemimage class if blogitem image is enabled
    var attachtype = $('span#attachtype',this).attr('rel');
    if(blogitemimage == '1' && attachtype == 'img' && blogitemimageSet == false){
      $(this).addClass('blogitemimage');
      $(this).prepend('<div id="blogitemimageText">Blogitem afbeelding:</div>');
      blogitemimageSet = true;
    } else {
      $(this).removeClass('blogitemimage');
    }  
        
    //new number
    $('input.inputPosition',this).val(num);
    num = num+1;
  })
}

//attachment show image url
function genUrlAttach(attachid,type){
  var url = $('#fxis_attachment-'+attachid+' span#url'+type).attr('rel');
  $('#url_attach-'+attachid).val(url);
  return;
}

//remove attachment
function removeAttachByID(attachid){
  $('#'+attachid).remove();   
  return; 
}

function checkGAenabled(){
  var gaEnabled = $('input[name=fxiscms_ga_enabled]:checked').val();
  if(gaEnabled == '0'){
    $('.row-gacode').hide();
    $('.row-gauser').hide();
    $('.row-gapass').hide();
    $('.row-gauser').hide();
  }
  if(gaEnabled == '1'){
    $('.row-gacode').show();
    $('.row-gauser').show();
    $('.row-gapass').show();
    $('.row-gauser').show();
  }
  reOrderFormRows();
}
function checkPCenabled(){
  var pcEnabled = $('input[name=fxiscms_pc_enabled]:checked').val();
  if(pcEnabled == '0'){
    $('.row-pcttl').hide();
    $('.row-pcupdate').hide();
  }
  if(pcEnabled == '1'){
    $('.row-pcttl').show();
    $('.row-pcupdate').show();
  }
  reOrderFormRows();
}

function checkGBenabled(){
  var gaEnabled = $('input[name=fxiscms_gb_enabled]:checked').val();
  if(gaEnabled == '0'){
    $('.row-gbpageid').hide();
    $('.row-gbitemsperpage').hide();
    $('.row-gbimgagesenabled').hide();
  }
  if(gaEnabled == '1'){
    $('.row-gbpageid').show();
    $('.row-gbitemsperpage').show();
    $('.row-gbimgagesenabled').show();
  }
  reOrderFormRows();
}

function reOrderFormRows(){
  $('div.fxiscmsform').each(function(){
    var zebra = 0;
    $('.row:visible',this).each(function(){
      $(this).removeClass('odd even').addClass(zebra % 2 ? 'even' : 'odd');
      zebra += 1;
    });    
  });
}

function reOrderRows(){
  //reset numbers and classes
  var zebra = 0;
  $('.sortableTable tbody tr').each(function(){
    $(this).removeClass('odd even').addClass(zebra % 2 ? 'even' : 'odd');
    $('td span.position',$(this)).text(zebra+1);
    $('td input.inputPosition',$(this)).val(zebra+1);
    
    //get id of this row
    var aid = $(this).attr("id");
    var reg = /^linksRow-([0-9]+)$/;
    var result = reg.exec(aid);
    var rowID = result[1];
    
    //clear disabled options
    $('select.parent option',$(this)).attr('disabled','');
    
    //padding for children rows. While iterating, also disable this row in parent rows selection
    var tempID = $(this).attr('id');
    var padding = 10;
    $('select.parent option[value="'+rowID+'"]',$(this)).attr("disabled","disabled");
    while($('select.parent',$('#'+tempID)).val() > 0){
      //disable current row in this row
      padding += 20;
      tempID = 'linksRow-'+$('select.parent',$('#'+tempID)).val();
      $('#'+tempID+' select.parent option[value="'+rowID+'"]').attr("disabled","disabled");
    }
    $('td.nameCol',$(this)).css('padding-left',padding+'px');

    zebra += 1;
  });
}

function positionChilds(){
  var children = new Array();
  $('.sortableTable tbody tr').each(function(){
    var inputParent = $('select.parent',$(this));
    if(inputParent.val() != 0){
      //we have a child
      var rowOrder = $('td input.inputPosition',$(this)).val();
      var rowID = $(this).attr('id');
      var rowParent = inputParent.val();
      //find level
      var level = 1;
      var parentTemp = rowParent;
      while($('.sortableTable tbody tr#linksRow-'+parentTemp+' select.parent').val() > 0){
        level += level;
        parentTemp = $('.sortableTable tbody tr#linksRow-'+parentTemp+' select.parent').val();
      }
      children[children.length] = new Array(level, rowParent, rowOrder, rowID);
    }
  });

/* this code messed up childs. probably became obsolete, weird
  //sort first level, then parent (inversed) and then order
  children.sort(sortChilds);
  for(num in children){
    var child = children[num];
    var tr = $('#'+child[3]);
    var parent = $('#linksRow-'+child[1]);
    tr.insertAfter(parent); 	
  }
*/

  reOrderRows();
  
}

function sortChilds(a,b){
  if(a[0] == b[0]){
    if(a[1] == b[1]){
      return (a[2] > b[2]) ? -1 : 1;
    }
    return (a[1] < b[1]) ? -1 : 1;
  }
  return (a[0] < b[0]) ? -1 : 1;
}

function getMax(array){
  max = 0;
  for(i in array){
    max = max > array[i] ? max : array[i];
  }
  return parseInt(max);
}
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
