var app;
var user = false;
var currentMenu1 = 0;
var currentMenu2 = 0;
var currentMenu3 = 0;

$(document).ready(function()
{
   app = fApplication.singleton();
   app.initialize({
      rpc: { decodeISO8601: false }
   });
   addListeners();
   document.onkeyup = KeyCheck;

   app.invoke('php:coneyAdmin::getLoginInfo', '',
              function(result) {
                 if(result)
                    loginUser(result);
              },
              function(exc) {
                 alert(exc.message);
              }
   );

   // Change the background-image after the first click to prevent it interfering with search text
   $('input.search_field').focus(function()
   {
      $('input.searchbg').attr('style','background:url(images/search_bg_empty.png) 0px 1px no-repeat');
      if($.browser.msie)
         $('div#searchbgIE').attr('style','background:url(images/search_bg_empty.png) 0px 1px no-repeat');
   });

   if(window.location.hash == "")
      window.location.hash = "#Home";
});

/**
 * Create the listeners
 */
function addListeners()
{
   app.addListener(
      'setLanguage',
      function(event)
      {
         app.invoke('php:coneySupport::setLanguage', event.target,
                    function(result) {
                       setLanguage(event.target,result);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'loginUser',
      function(event)
      {
         app.invoke('php:coneyAdmin::login', event.target,
                    function(result) {
                       loginUser(result);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'doSearch',
      function(event)
      {
         app.invoke('php:coneySearch::doSearch', event.target,
                    function(result) {
                       doSearch(result);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'addReaction',
      function(event)
      {
         app.invoke('php:coneyReaction::createTemplate', event.target,
                    function(result) {
                       addReaction(event.target,result);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'saveReaction',
      function(event)
      {
         app.invoke('php:coneyReaction::saveReaction', event.target,
                    function(result) {
                       saveReaction(event.target.id, result);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'deleteReaction',
      function(event)
      {
         app.invoke('php:coneyReaction::deleteReaction', event.target,
                    function(result) {
                       deleteReaction(event.target.id, result);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'logout',
      function(event)
      {
         app.invoke('php:coneyAdmin::logout','',
                    function(result) {
                       user = [];
                       removeEditButtons();
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'saveMenu',
      function(event)
      {
         app.invoke('php:coneyAdmin::saveMenu', event.target,
                    function(result) {
                       alert('Menu saved succesfully');
                       toggle(currentMenu1, currentMenu2, currentMenu3);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'saveAdminSettings',
      function(event)
      {
         app.invoke('php:coneyAdmin::saveAdminSettings', event.target,
                    function(result) {
                       alert("Settings saved succesfully");
                       toggle(currentMenu1, currentMenu2, currentMenu3);
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'sendNewsletter',
      function(event)
      {
         app.invoke('php:coneyNewsletter::sendNewsletter', event.target,
                    function(result) {
                       alert('Newsletter has been sent');
                       $('div.newsletter_send').find('input:checked').attr('checked','');
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
   app.addListener(
      'saveSubscriber',
      function(event)
      {
         app.invoke('php:coneyNewsletter::subscribe', event.target,
                    function(result) {
                       alert('Thank you for subscribing');
                       closeWindow($('.subscribeDiv').attr('id'));
                    },
                    function(exc) {
                       alert(exc.message);
                    }
         );
      }
   );
}

/**
 * Performs actions depending on the pressed key
 *
 * @param e
 */
function KeyCheck(e)
{
   var KeyID = (window.event) ? event.keyCode : e.keyCode;
   switch(KeyID)
   {
   case 13:
      if($('#login_div:visible').attr('id'))
         loginUser();
      return false;
      break;
   }
}

function track()
{
   var item = $('ul.menu > li[id='+currentMenu1+'] > a').text();
   if(currentMenu2)
   {
      item += "/" + $('#sub' + currentMenu1 + ' > ul > li[id='+currentMenu2+'] > a').text();

      if(currentMenu3)
         item += "/" + $('#sub' + currentMenu1 + ' > ul > li[id='+currentMenu2+'] > div[id='+currentMenu3+']').text();
   }

   if(item != "")
   {
      fApplication.singleton().googleTrack(item);
      fApplication.singleton().addHistory(item);
   }
}

function toggle(id1, id2, id3, callback)
{
   var oldid3 = id3;
   if(!id1)                   // Use current value(s)
   {
      if(!id2)
      {
         if(!id3) id3 = currentMenu3;
         id2 = currentMenu2;
      }
      id1 = currentMenu1;
   }
   else if(id1 == -1)         // Find parent for id2
   {
      var p = $("li#" + id2).parents('div.submenu');
      id1 = p.attr("id").substr(3, 100);
   }

   // For subsub just get the subsub content, else get whole content
   var full = true;
   var islist = $("li#" + id2).hasClass("news_list") || $("li#" + id2).hasClass("blog_list");
   if(islist) id3 = oldid3;

   if(id1 == currentMenu1 && id2 == currentMenu2 && id3 && !islist)
   {
      full = false;
   }
   else
   {
      if(!id2)
         id2 = $("#sub" + id1 + " > ul > li:first").attr("id") || 0;

      if(!id3)
         id3 =  $("li#" + id2 + " > div:first").attr("id") || 0;

      var menu = $('div.menu').find('ul.menu');
      menu.find('li.menu_item').attr('class','menu_item');
      menu.find('li[id=' + id1 + ']').attr('class','menu_item selected');

      var sub = $('#sub' + id1);
      if(currentMenu1 != id1)
      {
         $('div.submenu').hide().slideUp();
         if(sub.children().length)
            sub.slideDown();
      }
      sub.find('li').removeClass('selected');
      sub.find('#' + id2).addClass('selected');
   }

   if(currentMenu1 == id1 && currentMenu2 == id2 && (currentMenu3 == id3 && !islist) && callback == undefined)
      return;

   currentMenu1 = id1;
   currentMenu2 = id2;
   currentMenu3 = id3;

   app.invoke('php:coneyTemplate::getTemplate', { id1: id1, id2: id2, id3: id3, full: full },
      function(result) {
         if(full || result.header)   // subsub *could* return a fullpage iframe
         {
            $('.content').html(result.content);
            if(result.header)
               $('.header').show();
            else
               $('.header').hide();

            if($(".sub_content > iframe").length > 0)
               $(".bottom_ticker").hide();
            else
               $(".bottom_ticker").show();

            if($("#bottom_ticker").children())
               startticker();
            if($("#bottom_ticker2").children())
               startticker2();

            if($.browser.msie && $.browser.version == '6.0')
            {
               var img = $(".header_text").attr("img");
               $(".header_text").css("background-image", "none");
               $(".header_text").css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+img+"',sizingMethod='scale')");
            }
         }
         else
         {
            $('div.sub_content > div.right_content').remove();
            $('#resource').remove();
            if(result.resources)
               $('div.sub_content > div.left_content').append(result.resources);
            $('div.sub_content > div.left_content').after(result.content);
         }

         if(loggedIn())
            addEditButtons();

         if(callback)
            callback();

         track();
      }
   );
}

function toggleNewsletterEdit(id)
{
   $('.newsletter_send:visible').hide();
   $('.newsletter_send[id=newsletter_'+id+']').show();
}

/**
 * Redirect a subsub-div
 *
 * @param id
 */
function redirect(id)
{
   if(id != currentMenu3)
   {
      var swf = document.getElementById('cPath');
      if(swf)
         swf.childNodes[0].update(id);
   }

   toggle(currentMenu1, currentMenu2, id);
}

/**
 * Correctly show the blog/news page with the correct details-page open
 *
 * @param id
 * @param parent_id
 */
function switchItemDetails(id, parent_id)
{
   if($('div.itemDetail[id='+id+']').length)
   {
      $('div.itemDetail').hide();
      $('div.itemDetail[id='+id+']').show();
      return;
   }

   if(isNaN(parent_id * 1))
      parent_id = $('.menu_container li[class*=' + parent_id.substr(0,4) + ']').attr('id');

   toggle(-1, parent_id, undefined, function() {
      $('div.itemDetail').hide();
      $('div.itemDetail[id='+id+']').show();
   });
}

/**
 * Sets the language to the given lang
 *
 * @param lang
 * @param result
 */
function setLanguage(lang, result)
{
   if(!result)
      app.triggerEvent('setLanguage', lang);
   else
      window.location.href = window.location.protocol + "//" + window.location.hostname + "/?lang=" + lang.substr(0,2) + "#Home";
}

/**
 * Perform a search and show it's results
 *
 * @param result
 */
function doSearch(result)
{
   if(result) {
      $('div.bottom_content').hide();
      $('div.main').children('div').hide();
      if($('div#search_result').attr('id'))
         $('div#search_result').replaceWith(result);
      else
         $('div.main').append(result);
   }
   else {
      var search = $('input[name=search]').val();
      if(search)
         app.triggerEvent('doSearch',search);
   }
}

/**
 * Show the form to add a reaction
 *
 * @param id
 * @param result
 */
function addReaction(id,result)
{
   if(!result) {
      if($('#reaction'+id).attr('id'))
      {
         $('#reaction'+id).show();
         $('textarea[name=reaction_text]').focus();
      }
      else
         app.triggerEvent('addReaction',id);
   }
   else
      $('.content').append(result);
}

/**
 * Perform a save of a reaction
 *
 * @param id
 * @param result
 */
function saveReaction(id, result)
{
   if(!result) {
      value = $('textarea[name=reaction_text]').val();
      $(".add_reaction").remove();
      app.triggerEvent('saveReaction', {id: id, value: value});
   }
   else {
      alert(result);

      var item = $('div.itemDetail:visible');
      var id1 = item.attr('id');
      var id2 = item.parent().attr('id');
      toggle(currentMenu1, currentMenu2, currentMenu3, function() {
         switchItemDetails(id1, id2);
      });
   }
}

function deleteReaction(id, result)
{
   if(!result)
      app.triggerEvent('deleteReaction', { id: id });
   else {
      alert(result);

      var item = $('div.itemDetail:visible');
      var id1 = item.attr('id');
      var id2 = item.parent().attr('id');
      toggle(currentMenu1, currentMenu2, currentMenu3, function() {
         switchItemDetails(id1, id2);
      });
   }
}

/**
 * Show the login-form
 */
function showLogin()
{
   $('#login_div').find('[name=login_username]').val('');
   $('#login_div').find('[name=login_password]').val('');
   if($('#login_div:visible').attr('id'))
      $('#login_div').hide();
   else {
      $('#login_div').show();
      $('input[name=login_username]').focus();
   }
}

/**
 * Show the subscribe-form
 */
function showSubscribe()
{
   $('.subscribeDiv').toggle();
   $('.subscribeDiv').find('input:first').focus();
}

/**
 * Subscribe to the newsletter
 */
function saveSubscribe()
{
   var div = $('.subscribeDiv');
   var lang = div.attr('lang');
   var optin = div.find('[name=optinEmail]:checked');

   if(!optin.length)
   {
      alert(lang == 'NL' ? 'Om de nieuwsbrief te ontvangen moet u als gevolg van de Nederlandse wetgeving expliciet toestemming geven door het desbetreffende vakje aan te vinken.' :
                           'In order to receive the newsletter Dutch law requires you to explicitly grant permission to do so by checking the appropriate checkbox.');
      return;
   }

   var data = {};
   data['firstname'] = div.find('[name=subscribeFirstname]').val();
   data['lastname'] = div.find('input[name=subscribeLastname]').val();
   data['company'] = div.find('input[name=subscribeCompany]').val();
   data['email'] = div.find('input[name=subscribeEmail]').val();

   app.triggerEvent('saveSubscriber',{data: data});
}

/**
 * Close an open 'window' (popup-div)
 *
 * @param id
 */
function closeWindow(id)
{
   if($('#'+id+':visible').attr('id'))
      $('#'+id).hide();
}

/**
 * Perform the login
 */
function loginUser(result)
{
   if(!result) {
      var username = $('#login_div').find('[name=login_username]').val();
      var password = $('#login_div').find('[name=login_password]').val();
      if (!username) username = '';
      if (!password) password = '';

      app.triggerEvent('loginUser',{ email: username,
                                     password: password
                                   }
      );

      return false;
   }
   else {
      user = result;

      $('#sub9999 li').hide();
      if(loggedIn())
      {
         for(var i = 0; i < user.items.length; i++)
            $('#sub9999 li[class*=' + user.items[i] + ']').show();
         addEditButtons();
      }
   }
}

/**
 * Logout
 */
function logout()
{
   app.triggerEvent('logout');
}

/**
 * Check if a user is logged in
 *
 * @param result
 */
function loggedIn()
{
   return user ? true : false;
}

/**
 * Add the add/edit buttons after logging in
 */
function addEditButtons()
{
   if($('div#login_div:visible').attr('id'))
      $('div#login_div:visible').hide();

   var klikEdit = "openEditPage($(this),'edit'); return false;";
   var klikEditItem = "openEditPage($(this),'item'); return false;";
   var klikAdd = "openEditPage($(this),'add'); return false;";
   var edit = '<div class="admin_btn adminEdit" onclick="'+klikEdit+'">EDIT</div>';
   var editItem = '<div class="admin_btn adminEdit" onclick="'+klikEditItem+'">EDIT</div>';
   var editUserItem = '<div style="top:46px !important" class="admin_btn adminEdit" onclick="'+klikEditItem+'">EDIT TEXT</div>';
   var add = '<div class="admin_btn adminAdd" onclick="'+klikAdd+'">ADD</div>';
   var adminMenuItem = '<li id="9999" class="menu_item"><div class="l">.</div><a onclick="toggle(\'9999\'); return false" href="#">Mijn Coney</a><div class="r">.</div></li>';
   $('div.admin_btn').remove();

   if(user.rights < 2)
   {
      $('.cItemDetails').parent().append(add);
   }
   else
   {
      $('div.component').prepend(edit);
      $('div.resourceItem').append(edit);
      $('div.sub_content').append(add);
      $('div.header_text').append(add);
   }

   if(!$('ul.menu').find('li#9999').attr('id'))
      $('ul.menu').append(adminMenuItem);
   $('.cItemDetails').find('.itemDetail').append(editItem);
   $('.cUser p[id]').append(editUserItem);

   $('div.cPath').find('div.admin_btn').remove();

   $('#login_button').replaceWith('<a href="#" onclick="logout(); return false;" id="logout_button">Logout</a>' +
                                  '<a href="#" onclick="toggle(9999); ;return false;" id="admin_button"> - Mijn Coney</a>');
}

/**
 * Remove the add/edit buttons after logging out
 */
function removeEditButtons()
{
   if(currentMenu1 == 9999)
      toggle(1, 0, 0, removeEditButtons);
   else
   {
      $('#logout_button').replaceWith('<a href="#" onclick="showLogin(); return false;" id="login_button">Login</a>');
      $('#admin_button').remove();
      $('.admin_btn').remove();
      $('#9999').remove();
   }
}

/**
/**
 * Open the edit form in a new window
 *
 * @param id
 * @param mode
 */
function openEditPage(item, mode)
{
   if(mode == 'add') {
      var id = (item.parents('.header_text').attr('id')
                ? item.parents('.header_text').attr('id')
                : (item.parents('.sub_content').attr('id') == 0
                   ? item.parents('.main').attr('id')
                   : item.parents('.sub_content').attr('id')));

      if($(item).parent('.cUser').attr('id')) {
         var parent = $(item).parent('.cUser').attr('id');
         var type = 'text';
      }

      if(item.parents('.header_text').attr('id'))
         var type = 'header';
      if(item.parent('.sub_content').attr('type') == 'blog_list' )
         var type = 'blog';
      else if(item.parent('.sub_content').attr('type') == 'news_list')
         var type = 'news';
      else if(item.parent('.sub_content').attr('type') == 'publ_list')
         var type = 'publication';
      else if(item.parent('.sub_content').attr('type') == 'contact_list' || item.parent('.sub_content').attr('type') == 'admin_user')
         var type = 'user';
   }
   else if(mode == 'edit') {
      var id = item.parent().attr('id');
      if(item.parent('.cUser').attr('id'))
         var user = true;

      var parent = (item.parents('.sub_content').attr('id') == 0
                    ? item.parents('.main').attr('id')
                    : item.parents('.sub_content').attr('id'));
   }
   else if(mode == 'item') {
      var type = 'item';
      var id = item.parent().attr('id');
      var parent = item.parents('.cItemDetails').attr('id');
   }
   else if(mode == 'menu') {
      var id = 'new';
   }
   else if(mode == 'subscribers') {
      mode = 'newsletter';
      var id = 'subscribe';
   }

   if(loggedIn() && id)
   {
      newwindow=window.open('edit.php?id='+id+'&mode='+mode
                               +(user ? '&user=true' : '')
                               +(parent ? '&parent='+parent : '')
                               +(type ? '&type='+type : ''),
                            'edit','scrollbars=1,height=720,width=600');
      if (window.focus) {newwindow.focus()}
      return false;
   }
}

/**
 * Javascript validation of the saving of admin-settings
 */
function saveAdminSettings()
{
   if(!loggedIn())
      return false;
   var data = {}
   data['email'] = $('div.sub_content').find('input[name=admin_email]').val();
   data['pass1'] = $('div.sub_content').find('input[name=admin_password]').val();
   data['pass2'] = $('div.sub_content').find('input[name=admin_password2]').val();

   if(data['email'] == '' || !data['email'])
      alert('Please enter an email address');
   else if(data['pass1'] != data['pass2'])
      alert('Passwords do not match');
   else
      app.triggerEvent('saveAdminSettings',{data: data});
}

/**
 * Grab data for saving menu-item list and send to the backend
 */
function saveMenu()
{
   if(!loggedIn())
      return false;
   var data = {};
   $('.sub_content').find('tr.menu_row').map(function() {
      data[$(this).attr('id')] = {};
      data[$(this).attr('id')]['NL'] = $(this).find('input[name=NL]').val();
      data[$(this).attr('id')]['EN'] = $(this).find('input[name=EN]').val();
      data[$(this).attr('id')]['banner'] = $(this).find('input[name=banner]').val();
      data[$(this).attr('id')]['content'] = $(this).find('select[name=content]').val();
      data[$(this).attr('id')]['viz'] = $(this).find('select[name=viz]').val();
      data[$(this).attr('id')]['sequence'] = $(this).find('select[name=sequence]').val();
   });
   app.triggerEvent('saveMenu',{data: data});
}

/**
 * Send the newsletter
 */
function sendNewsletter()
{
   if(!loggedIn())
      return false;
   var data = {};
   data['id'] = '';
   data['subject'] = $('div.sub_content').find('[name=subject]').val();
   data['language'] = $('div.sub_content').find('[name=language]').val();
   data['intro'] = $('div.sub_content').find('[name=intro]').val();
   $('div.sub_content').find('.newsletter_send:visible').find(':checkbox:checked').each(function() {
      data['id'] += $(this).val() + ',';
   });
   data['id'] = data['id'].substring(0,data['id'].length-1);

   if(data['id'] == '')
      alert('Please select at least 1 news-item');

   app.triggerEvent('sendNewsletter',{data: data});
}

/*
 * Perform the given action on the given checkboxes
 *
 * @param name
 * @param action
 */
function checkToggle(selector, action)
{
   if(action == 'all')
     $(selector).find(':checkbox').attr('checked',true);
   else if(action == 'none')
      $(selector).find(':checkbox').attr('checked',false);
   else if(action == 'toggle') {
      $(selector).find(':checkbox').each(function() {
         $(this).attr('checked', !$(this).attr('checked'));
      });
   }
}
