$(document).ready(function(){
  if(framework.isAdminLoggedIn)
    showEditInPlaceNav();
    
  bindAJAX();
  bindAJAXForm();
  bindServerBrowser();
  bindWYSIWYG();
  bindAddNewChildPage();
  bindDeleteChildPage();
  bindApplyNewSortOrder();
});

function bindSortChildNodes()
{
  $('#childNodes > ul li').each(function(){
    $(this).attr('initialIndex', $('#childNodes > ul li').index(this) );
  });
  
  $('#childNodes > ul').sortable({update: function(event, ui){
    $('#applyNewSortOrderDiv').show();
  }});
}

function bindApplyNewSortOrder()
{
  $('#applyNewSortOrderBtn').live('click', function(){
      var postData = '&order=';
      
      $('#childNodes > ul li').each(function(){
        postData +=$(this).attr('initialIndex')+'|';
      });
      
      var applyNewSortOrderURL = framework.siteHandlerURL+framework.currentController+'/applyNewSortOrder/?controller='+framework.currentController+'&function='+framework.currentFunction+postData;

      ajaxRequest(this, applyNewSortOrderURL,'',function(data){
        $('#childNodes').html( data );
        bindSortChildNodes();
        $('#applyNewSortOrderDiv').hide();
      });
  });
}

function bindServerBrowser()
{
  $('.serverBrowser').click(function(){
    var browser = window.open(framework.siteURL+'js/fckeditor/editor/plugins/ajaxfilemanager/ajaxfilemanager.php','serverBrowser','width=782, height=440');
    var target = $(this).attr('target');
    browser.focus();

    window.SetUrl = function(url){
      $(target).attr('value', url);
    }
  });
}

function bindAJAX()
{
  $('a.ajax').live('click',function(){

    ajaxRequest(this,'' ,'',function(response){

      bindServerBrowser();
      bindWYSIWYG();

      bindAJAXForm();
    });

    return false;
  });
}

function bindWYSIWYG()
{
  $('.editor').each(function(){
    if(( $(this).css('display') == 'none' ) || ( $(this).parent().css('display') == 'none' ) || ( $(this).parent().parent().css('display') == 'none' ) || ( $(this).parent().parent().parent().css('display') == 'none' ))
      return;

    if(this.id == '')
      this.id = this.tagName.toLowerCase()+'Index'+$('.editor').index(this);

    switchToEditor(this.id);
  });
}

function bindAJAXForm()
{
  $('form.ajax').unbind();
  $('form.ajax').submit(function(){

    $(this).find('.editor').each(function(){
      FCKeditorAPI.GetInstance(this.id).UpdateLinkedField();
    });

    ajaxRequest(this,'' ,'',function(response){ bindAJAXForm(); });

    return false;
  });
}

function hideEditPageProperties(obj)
{
  $('#editPageProperties').hide();
  var target = $(obj).parent().parent().parent().attr('target');
  $(target).show();
}

function hideEditSiteProperties(obj)
{
  $('#editSiteProperties').hide();
  var target = $(obj).parent().parent().parent().attr('target');
  $(target).show();
}

function hideEditContent(obj)
{
  var parent = $(obj).parent().parent().parent();
  parent.hide();
  
  var target = parent.parent().attr('target');
  $(target).show();
}


function showEditInPlaceNav()
{
  $('.editable').each(function(){
  
    var id = 'editable'+$('.editable').index(this);
    
    $(this).attr('id', id);
    
    var contentName = $(this).attr('contentname');
    var contentType = $(this).attr('contenttype');
    
    var editContentNav = '<a href="javascript:void(false);" datasrc="#'+id+'" class="getEditContent"><strong>Edit Content</strong></a>';
    var editPagePropertiesNav = '<a href="javascript:void(false);" datasrc="#'+id+'" class="getEditPageProperties"><strong>Edit Page Properties</strong></a>';
    var editSitePropertiesNav = '<a href="javascript:void(false);" datasrc="#'+id+'" class="getEditSiteProperties"><strong>Edit Site Properties</strong></a>';

    var editInPlaceNav = '<div class="editInPlaceNav" style="margin-bottom: 10px;">'+editContentNav;
    
    if(contentType == 'mainContents')
      editInPlaceNav+=' | '+editPagePropertiesNav+' | '+editSitePropertiesNav;

    editInPlaceNav +='</div>';
    
    var saveContentURL = framework.siteHandlerURL+framework.currentController+'/saveContent/?contentType='+contentType+'&contentName='+contentName;
    var editInPlaceContentEditor = '<div class="editContent" style="display:none;"><form action="'+saveContentURL+'" method="post" class="ajax" afterAjax="window.location.reload()" ajaxOutput="#'+id+'-editContentStatus" style="position:absolute;background-color:#ffffff;padding-bottom:10px"><textarea class="editor" id="'+id+'-textArea" name="newContent"></textarea><div><input class="save" type="submit" value="Save"/><input class="cancel" value="Cancel" type="button" onclick="hideEditContent(this)"/><div id="'+id+'-editContentStatus"></div></div></form></div>';

    var editInPlacePageProperties = '';
    var editInPlaceSiteProperties = '';
    
    var savePagePropertiesURL = framework.siteHandlerURL+framework.currentController+'/savePageProperties/?controller='+framework.currentController+'&function='+framework.currentFunction;
    var saveSitePropertiesURL = framework.siteHandlerURL+framework.currentController+'/saveSiteProperties/';
    
    if(contentType == 'mainContents')
    {
      editInPlacePageProperties = '<div id="editPageProperties" style="display:none"><form class="ajax" action="'+savePagePropertiesURL+'" method="post" ajaxOutput="#editPagePropertiesStatus" afterAjax="window.location.reload()"><div class="content"></div><input type="submit" value="Save" /><input type="button" value="Cancel" onclick="hideEditPageProperties(this)"/><div id="editPagePropertiesStatus"></div></form></div>';
      editInPlaceSiteProperties = '<div id="editSiteProperties" style="display:none"><form class="ajax" action="'+saveSitePropertiesURL+'" method="post" ajaxOutput="#editSitePropertiesStatus" afterAjax="window.location.reload()"><div class="content"></div><input type="submit" value="Save" /><input type="button" value="Cancel" onclick="hideEditSiteProperties(this)"/><div id="editSitePropertiesStatus"></div></form></div>';
    }
    
    var editInPlace = '<div class="editInPlace" target="#'+id+'">'+editInPlaceNav+editInPlaceContentEditor+editInPlacePageProperties+editInPlaceSiteProperties+'</div>';

    $(this).before(editInPlace);
  });
  
  bindEditContent();
  bindEditPageProperties();
  bindEditSiteProperties();
}

function switchToEditor(editAreaId)
{
  var oFCKeditor = new FCKeditor( editAreaId );
	oFCKeditor.BasePath = framework.siteURL+'js/fckeditor/';
  oFCKeditor.ToolbarSet = 'MyToolbar';

  var width = $('#'+editAreaId).css('width');
  var height = $('#'+editAreaId).css('height');

  if((parseInt(width) < 500) || (width == 'auto'))
    width = '500';

  if((parseInt(height) < 350) || (height == 'auto'))
    height = '350';

	oFCKeditor.Width = width;
	oFCKeditor.Height = height;
	oFCKeditor.ReplaceTextarea();

  return oFCKeditor;
}

function ajaxRequest(obj, url, postData, successCallBackFunction, errorCallBackFunction)
{
  var ajaxOutput = $(obj).attr('ajaxOutput');
  var afterAjax = $(obj).attr('afterAjax');
  var onAjaxWait = $(obj).attr('onAjaxWait');
  
  if(url == '')
  {
    url = $(obj).attr('href');

    if(url == undefined)
    {
      url = $(obj).attr('action');
      if(url != undefined)
        postData +='&'+$(obj).serialize();
    }
      
    if((url == undefined)  && (url.indexOf('javascript') != -1 ))
      url = window.location.href;
  }
  
  if(ajaxOutput != undefined)
  {
    if(onAjaxWait != undefined)
      $(ajaxOutput).html(onAjaxWait);
    else
      $(ajaxOutput).html('Sending AJAX request please wait ...');
  }

  $.ajax({
        url: url,
        type: "POST",
        data: "ajaxRequest=true&"+postData,
        cache: false,
        success: function(data, textStatus){

          if(ajaxOutput != undefined)
            $(ajaxOutput).html(data);

          if(successCallBackFunction != undefined)
            eval('successCallBackFunction(data, textStatus)');

          if(afterAjax != undefined)
            eval(afterAjax);

        },
        error: function(XMLHttpRequest, textStatus, errorThrown){

          if(errorCallBackFunction != undefined)
            eval('errorCallBackFunction(XMLHttpRequest, textStatus, errorThrown)');
        }
     }
  );
}

function bindEditContent(controller)
{
  $('.getEditContent').click(function(){
    var editInPlaceParent = $(this).parent().parent();
    var targetElement = editInPlaceParent.attr('target');
    var targetElementId = $(targetElement).attr('id');
    
    var contentName = $(targetElement).attr('contentname');
    var contentType = $(targetElement).attr('contenttype');
    
    var requestURL = framework.siteHandlerURL+framework.currentController+'/getContent/?contentType='+contentType+'&contentName='+contentName;

    ajaxRequest(this, requestURL,'',function(data){

      $(targetElement).hide();
      $('#'+targetElementId+'-status').html('');
      
      editInPlaceParent.find('#editPageProperties').hide();
      editInPlaceParent.find('.editContent').show();
      
      var textArea = editInPlaceParent.find('.editContent textarea');
      textArea.val(data);
      
      if( $('#'+textArea.attr('id')+'___Config').length == 0)
        switchToEditor(textArea.attr('id'));
      else
        FCKeditorAPI.GetInstance(textArea.attr('id')).SetHTML(data);
    })
  });
}

function bindEditPageProperties(controller)
{
  $('.getEditPageProperties').click(function(){
    var editInPlaceParent = $(this).parent().parent();
    var targetElement = editInPlaceParent.attr('target');
    
    var requestURL = framework.siteHandlerURL+framework.currentController+'/getPageProperties/?controller='+framework.currentController+'&function='+framework.currentFunction;

    ajaxRequest(this, requestURL,'',function(data){
      $(targetElement).hide();
      editInPlaceParent.find('.editContent').hide();
      editInPlaceParent.find('#editSiteProperties').hide();
      editInPlaceParent.find('#editPageProperties .content').html(data);
      editInPlaceParent.find('#editPageProperties').show();
      bindServerBrowser();
      bindSortChildNodes();
    })
    
  });
}

function bindEditSiteProperties()
{
  $('.getEditSiteProperties').click(function(){
    var editInPlaceParent = $(this).parent().parent();
    var targetElement = editInPlaceParent.attr('target');

    var requestURL = framework.siteHandlerURL+framework.currentController+'/getSiteProperties/';

    ajaxRequest(this, requestURL,'',function(data){
      $(targetElement).hide();
      editInPlaceParent.find('.editContent').hide();
      editInPlaceParent.find('#editPageProperties').hide();
      editInPlaceParent.find('#editSiteProperties .content').html(data);
      editInPlaceParent.find('#editSiteProperties').show();
      bindServerBrowser();
      bindSortChildNodes();
    })

  });
}

function bindAddNewChildPage()
{
  $('#addNewChildPage').live('click', function(){
    $('#addNewChildPageDiv').show();
  });
  
  $('#addNewChildPageBtn').live('click', function(){
    if($('#newPage').attr('value').trim() == '')
      return;
      
    var addNewChildPageURL = framework.siteHandlerURL+framework.currentController+'/addNewChildPage/?controller='+framework.currentController+'&function='+framework.currentFunction+'&newPage='+$('#newPage').attr('value').trim();
    
    ajaxRequest(this, addNewChildPageURL,'',function(data){
      $('#childNodes').html( data );
      bindSortChildNodes();
    });
  });
  
  $('#cancelAddNewChildPageBtn').live('click',function(){
    $('#addNewChildPageDiv').hide();
  });
}

function bindDeleteChildPage()
{
  $('.deleteChildPage').live('click', function(){
    if(confirm('Are you shure you want to delete this page?'))
    {
      var controller = $(this).attr('controller');
      var func = $(this).attr('function');
      
      var deleteChildPageURL = framework.siteHandlerURL+framework.currentController+'/deleteChildPage/?controller='+controller+'&function='+func;

      ajaxRequest(this, deleteChildPageURL,'',function(data){
        $('#childNodes').html( data );
        bindSortChildNodes();
      });
    }
  });
}
