// custom Layout functions
var customLayout = {
  rootUrl: jQuery('#root_url').attr('value'),

  ajaxManager: null,
  init: function(rootUrl, ajaxManager){ 
    this.rootUrl = rootUrl;
    this.ajaxManager = ajaxManager;
    jQuery('.row > ul > li > ul').sortable({
      handle: '.handle',
      placeholder: 'sortHelper',
      forcePlaceholderSize: true,
      revert: true,
      opacity: 0.4,
      connectWith: '.row > ul > li > ul'
    }); 
    jQuery('#page').sortable({
      handle: '.rowhandle',
      placeholder: 'sortHelper',
      forcePlaceholderSize: true,
      revert: true,
      opacity: 0.4
    });
    jQuery('#menu > ul').sortable({
      handle: '.handle',
      placeholder: 'menuSortHelper',
      forcePlaceholderSize: true,
      revert: true,
      dropOnEmpty: true,
      opacity: 0.4
    }); 
    jQuery('#menu > ul > li > ul').sortable({
      handle: '.handle',
      placeholder: 'submenuSortHelper',
      forcePlaceholderSize: true,
      revert: true,
      dropOnEmpty: true,
      opacity: 0.4
    });   
		
    // Dragging a block from column to column -> change width
    jQuery('.row > ul > li > ul').bind('sortover', function(event, ui) {
      //console.log(ui);
      var placeHolderSize = $(event.target).width();

      jQuery(ui.helper).width(placeHolderSize);
    }); 
    
    // Save layout
    jQuery('#main').bind('sortstop', function(event, ui) {
      customLayout.ajaxManager.abort();
      customLayout.save();
    });

    // Save layout for sidebar
    jQuery('#sidebarblocks').bind('sortstop', function(event, ui) {
      ajaxManager.abort();
      customLayout.save(ajaxManager);
    }); 
    
    // new row form
    jQuery('#newRowForm .btn2').live('click',function(){
      return customLayout.saveRow(this);
    });

    // disable click if has class inactive
    jQuery('.editblock .close').live('click', function(e){
      if(jQuery(this).hasClass('inactive')){
        return false;
      }
    });
    
    // Confirm deletes
    // delete block
    jQuery('.editblock .close').live('click', function(){
      var answer = confirm(jQuery.i18n._('delete_widget'));
      if(answer){

        var deleteButton = jQuery(this);
        jQuery.get(deleteButton.attr('href'));
        deleteButton.parent().parent().parent().parent().remove();
      }
      return false;
    });
    // Delete row
    jQuery('.row .close.active').live('click', function(){
      var answer = confirm(jQuery.i18n._('delete_row'));
      if(answer){
        var deleteButton = jQuery(this);
        jQuery.get(deleteButton.attr('href'), function(data){
        if('success' == data){
          var rows = jQuery('#page .row');
          if(rows.length < 3){
            jQuery('#page .row .rowhandle').toggle();
          }
          deleteButton.parent().parent().remove();
        }
      });
      }
      return false;
    });
  },
  save: function(){
    var path = window.location.pathname;
    path = this.rootUrl + 'ajax/updatecustomcontent' + path;
    var pageSetup = customLayout.getSetup();
    var dataString =  jQuery.phpSerialize(pageSetup);
    
    // show indicator message
    site.updateStatusIndicator(jQuery.i18n._('content_layout_saving'), false);
    
    // TODO Check if the row has undeletables (news item)
    
    
    // Add ajax request to the queue
    this.ajaxManager.add({ 
      type: "POST",
      data: ({data: dataString}),
      url: path, 
      success: function(data){
        site.updateStatusIndicator(jQuery.i18n._('content_layout_saved'), true);
        //console.log(data);
      } 
    });
  },
  getSetup: function(){
    var rows = [];
    jQuery('.row').each(function (i) {  
      var rowId = jQuery(this).attr('id');
      rows[rowId] = [];

      jQuery(this).find('.col').each(function (ii) {
        var colId = jQuery(this).attr('id');

        rows[rowId][colId] = jQuery(this).attr('id');
        rows[rowId][colId] = [];
        jQuery(this).find('.block').each(function (iii) {
          rows[rowId][colId][iii] = jQuery(this).attr('id');

        });

      });
    });
    return rows;

  },
  // save new row
  saveRow: function(element) {
    var total_columns = jQuery(element).attr('href');
    jQuery('#row_columns').val(total_columns);
    var form = jQuery('#newRowForm');
    var dataString = form.serialize();  
    
    //alert (dataString);return false;  
    jQuery.ajax({  
      type: "POST",  
      url: form.attr('action'),  
      data: dataString,
      success: function(html){
        var rows = jQuery('#page .row');
        if(rows.length == 1){
          jQuery('#page .row .rowhandle').toggle();
        }
        
        jQuery('#page').append(html);
        customLayout.init(customLayout.rootUrl, customLayout.ajaxManager);
        jQuery(".jqmWindow").jqmHide();
      }    
    });
    return false;
  }
}

// Navigarion functions
var navigation = {
  menuItems: 'ul#navigationlist > li > a.page',
  subMenuItems: 'ul#navigationlist > li > ul > li > a.page',
  rootUrl: jQuery('#root_url').attr('value'),

  ajaxManager: null,
  init: function(rootUrl, ajaxManager) {
    this.rootUrl = rootUrl;
    this.ajaxManager = ajaxManager;
    // Save navigation
    jQuery('#sidebar #menu').bind('sortstop', function(event, ui) {
      navigation.ajaxManager.abort();
      navigation.save();
    });
    
    // Confirm delete
    jQuery('#navigationlist .close').live('click', function(){
      var answer = confirm(jQuery.i18n._('delete_page'));
      if(!answer){
        return false;
      }
    });
  },
  save: function(){
    path = this.rootUrl + 'ajax/updatenavigation';
    var pageSetup = navigation.getOrder();
    var dataString =  jQuery.phpSerialize(pageSetup);
    
    // show indicator message
    site.updateStatusIndicator(jQuery.i18n._('navigation_order_saving'), false);
    
    // Add ajax request to the queue
    navigation.ajaxManager.add({ 
      type: "POST",
      data: ({data: dataString}),
      url: path, 
      success: function(data){
        site.updateStatusIndicator(jQuery.i18n._('navigation_order_saved'), true);
        //console.log(data);
      }
    });
  },
  getOrder: function(){
    var navItems = [];
    jQuery('#navigationlist > li').each(function (i) {  
      var navId = jQuery(this).attr('id');
      navItems[navId] = [];

      jQuery(this).find('li').each(function (ii) {
        navItems[navId][ii] = jQuery(this).attr('id');
      });
    });
    return navItems;

  },
  getMenuItems: function() {
    return jQuery(this.menuItems);
  },
  getSubMenuItems: function() {
    return jQuery(this.subMenuItems);
  },
  setBackgroundColor: function(hsb, hex, rgb) {
    navigation.getMenuItems().css('backgroundColor', '#' + hex);
    jQuery('#footermenu .content').css('backgroundColor', '#' + hex);
    
    // set line color
    navigation.setBorderColor(hsb, hex, rgb);
  },
  getBackgroundColor: function() {
    if ( navigation.getMenuItems().length > 0 ) {
      return colorHelper.rgbToHex(navigation.getMenuItems().css('backgroundColor'));
    } 
    return '#ffffff';
  },
  setBorderColor: function(hsb, hex, rgb) {
    var borderColor = colorHelper.getDarkerShade(hex);
    navigation.getMenuItems().css('borderTopColor', '#' + borderColor);
    navigation.getMenuItems().css('borderBottomColor', '#' + borderColor);
  },
  getBorderColor: function(hsb, hex, rgb) {
    if ( navigation.getMenuItems().length > 0 ) {
      return colorHelper.rgbToHex(navigation.getMenuItems().css('borderTopColor'));
    } 
    return '#ffffff';
  },
  setTextColor: function(hsb, hex, rgb) {
    navigation.getMenuItems().css('color', '#' + hex);
    jQuery('#footermenu .content ul li a').css('color', '#' + hex);
    
  },
  getTextColor: function() {
    if ( navigation.getMenuItems().length > 0 ) {
      return colorHelper.rgbToHex(navigation.getMenuItems().css('color'));
    } 
    return '#ffffff';
  },
  setSubBackgroundColor: function(hsb, hex, rgb) {
    navigation.getSubMenuItems().css('backgroundColor', '#' + hex);
    
    // set line color
    navigation.setSubBorderColor(hsb, hex, rgb);
  },
  getSubBackgroundColor: function() {
    if ( navigation.getSubMenuItems().length > 0 ) {
      return colorHelper.rgbToHex(navigation.getSubMenuItems().css('backgroundColor'));
    } 
    return '#ffffff';
  },
  setSubBorderColor: function(hsb, hex, rgb) {
    var borderColor = colorHelper.getDarkerShade(hex);
    navigation.getSubMenuItems().css('borderTopColor', '#' + borderColor);
    navigation.getSubMenuItems().css('borderBottomColor', '#' + borderColor);
  },
  getSubBorderColor: function(hsb, hex, rgb) {
    if ( navigation.getSubMenuItems().length > 0 ) {
      return colorHelper.rgbToHex(navigation.getSubMenuItems().css('borderTopColor'));
    }
    return '#ffffff';
  },
  setSubTextColor: function(hsb, hex, rgb) {
    navigation.getSubMenuItems().css('color', '#' + hex);
  },
  getSubTextColor: function() {
    if ( navigation.getSubMenuItems().length > 0 ) {
      return colorHelper.rgbToHex(navigation.getSubMenuItems().css('color'));
    } 
    return '#ffffff';
  }
}

// widgetContent functions
var widget = {
  rootUrl: jQuery('#root_url').attr('value'),

  init: function(rootUrl) {
    this.rootUrl = rootUrl;
    // Save new widget
    jQuery('#widgetForm .btn2').live('click',function(){
      return widget.save(this);
    });
    
    // widget content save
    jQuery('.widgetContentForm').live('click',function(){
      return widget.saveContent('#widgetContentForm');
    });
    
    // Add linkswidget link
    jQuery('#edit_links .jmqAdd').live('click', function(){
      return widget.widgetLinksAdd(this);
    });
    
    // Delete linkswidget link
    jQuery('#edit_links .close').live('click', function(){
      return widget.widgetLinksDelete(this);
    });
    
    // save linkswidget 
    jQuery('#widgetLinksForm .widgetLinksForm').live('click', function(){
      return widget.widgetLinksSave(this);
    });
  },
  
  saveContent: function(formName){
    //update textareas from wysiwig
    try{
      jQuery.fck.update();
    } catch(err){
      //console.log(err);
    }
    var form = jQuery(formName);
    var dataString = form.serialize();  
    var widget_id  = jQuery('#widget_id').attr('value'); 
    
    //alert (dataString);return false;  
    jQuery.ajax({  
      type: "POST",
      url: form.attr('action'),  
      data: dataString,
      widget_id: widget_id,
      success: function(html){
        jQuery('#block-' + this.widget_id).after(html).remove();
        page.fixImageWidths();
        jQuery(".jqmWindow").jqmHide();
      }    
    });
    return false;
  },
  // New widget save
  save: function(element) {
    var form = jQuery('#widgetForm');
    // update widget_type
    var type_id = jQuery(element).attr('href');
    jQuery('#widget_widget_type_id').val(type_id);

    var dataString = form.serialize();  
    var column     = jQuery('#widget_column_id').attr('value'); 
    
    
    jQuery.ajax({  
      type: "POST",  
      url: form.attr('action'),  
      data: dataString,
      column_id: column,
      success: function(html){  
        jQuery('#col-' + this.column_id + '> ul').append('<li>' + html + '</li>');
        var resultBlock = jQuery(html);
        var editUrl = resultBlock.find('a.edit').attr('href');
        if(editUrl == null){
          jQuery('#jqModal').jqmHide();
        } else {
          jQuery('#jqModal').load(editUrl, {}, jqmFunctions.jqmLoaded);
        }
      }    
    });
    return false;
  },
  // Links widget - ADD
  widgetLinksAdd: function(element) {
    var title = jQuery(element).parent().parent().find('#link_title');
    var url = jQuery(element).parent().parent().find('#link_url');

    //if(url.substr(0,7) != 'http://') url.val('http://' + url.val());
    if(title.val() == '' || url.val() == '' || url.val() == 'http://'){
      alert(jQuery.i18n._('edit_links_error'));
      return false;
    }
    
    // Validate url
		var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
		if(!regexp.test(url.val())){
      alert(jQuery.i18n._('edit_links_invalid_url'));
      return false;
    }
    
    // Return HTML
    var html = jQuery('<li class="edit_link_item"><a class="link" href="' + url.val() + '">' + title.val() + '</a><a href="#" class="jqmDelete close"></a><a class="handle" title="Sleep om te ordenen" href="#"><div><!-- --></div></a></li>');
    jQuery('#edit_links_list').append(html.hide().fadeIn(2000));
    
    url.val('http://');
    title.val('');
    
    return false;
  },
  // Links widget - DELETE
  widgetLinksDelete: function(element) {
    jQuery(element).parent().remove();

     return false;
  },
  // Links widget - SAVE
  widgetLinksSave: function(element) {
    var links = jQuery('#widget_links_links');
    var linksArray = [];
    jQuery('#edit_links_list > .edit_link_item').each(function(i){
      var linkItem = jQuery(this).find('.link');
      linksArray[i] = [];
      linksArray[i]['url'] = linkItem.attr('href');
      linksArray[i]['title'] = linkItem.html();
    });
        
    links.val(jQuery.phpSerialize(linksArray));
    
    return widget.saveContent('#widgetLinksForm');
    
    return false;
  }
	
}

// site functions
var site = {
  saveSettings: function() {
    var settingsArray = [];
    settingsArray['styles'] = site.getStylesSetup();    
    jQuery('#site_theme_settings').val(jQuery.phpSerialize(settingsArray));
    return false;
    
  },
  updateStatusIndicator: function(message, fadeout){
    // update status indicator
    if(fadeout){
      jQuery('#indicator').html(message).idle(1500).fadeOut('slow');
      jQuery('.close').removeClass('inactive');
      jQuery('#preview').removeClass('inactive');

    } else {
      jQuery('#indicator').html(message).fadeIn('slow');
      jQuery('.close').addClass('inactive');
      jQuery('#preview').addClass('inactive');
    }
  },
  setBackgroundColor: function (hsb, hex, rgb) {
      jQuery('body').css('backgroundColor', '#' + hex);
      jQuery('#footer .content').css('backgroundColor', '#' + colorHelper.getDarkerShade(hex));
      
  },
  getBackgroundColor: function() {
    return colorHelper.rgbToHex(jQuery('body').css('backgroundColor'));
  },
  loadSettings: function(){
    
    // Colorpickers
    jQuery('#background_color').ColorPicker({ 
      color: site.getBackgroundColor(), 
      onChange: function(hsb, hex, rgb) {
        site.setBackgroundColor(hsb, hex, rgb);
        jQuery('#background_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit: site.setBackgroundColor 
    }).find('div').css('backgroundColor', site.getBackgroundColor());
    
    jQuery('#text_color').ColorPicker({ 
      color: colorHelper.rgbToHex(jQuery('body').css('color')), 
      onChange: function(hsb, hex, rgb) {
        jQuery('body').css('color', '#' + hex);
        jQuery('p').css('color', '#' + hex);
        
        jQuery('#text_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit: site.setBackgroundColor 
    }).find('div').css('backgroundColor', colorHelper.rgbToHex(jQuery('body').css('color')));
    
    jQuery('#menu_background_color').ColorPicker({  
      color: navigation.getBackgroundColor(), 
      onChange: function(hsb, hex, rgb) {
        navigation.setBackgroundColor(hsb, hex, rgb);
        jQuery('#menu_background_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit:  navigation.setBackgroundColor 
    }).find('div').css('backgroundColor', navigation.getBackgroundColor());
    
    jQuery('#menu_text_color').ColorPicker({  
      color: navigation.getTextColor(), 
      onChange: function(hsb, hex, rgb) {
        navigation.setTextColor(hsb, hex, rgb);
        jQuery('#menu_text_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit: navigation.setTextColor 
    }).find('div').css('backgroundColor', navigation.getTextColor());
    
    jQuery('#menu_border_color').ColorPicker({  
      color: navigation.getBorderColor(), 
      onChange: function(hsb, hex, rgb) {
        navigation.setBorderColor(hsb, hex, rgb);
        jQuery('#menu_border_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit: navigation.setBorderColor 
    }).find('div').css('backgroundColor', navigation.getBorderColor());
    
    jQuery('#submenu_background_color').ColorPicker({  
      color: navigation.getSubBackgroundColor(), 
      onChange: function(hsb, hex, rgb) {
        navigation.setSubBackgroundColor(hsb, hex, rgb); 
        jQuery('#submenu_background_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit:  navigation.setSubBackgroundColor 
    }).find('div').css('backgroundColor', navigation.getSubBackgroundColor());
    
    jQuery('#submenu_text_color').ColorPicker({  
      color: navigation.getSubTextColor(), 
      onChange: function(hsb, hex, rgb) {
        navigation.setSubTextColor(hsb, hex, rgb);
        jQuery('#submenu_text_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit: navigation.setSubTextColor 
    }).find('div').css('backgroundColor', navigation.getSubTextColor());
    
    jQuery('#submenu_border_color').ColorPicker({  
      color: navigation.getSubBorderColor(), 
      onChange: function(hsb, hex, rgb) {
        navigation.setSubBorderColor(hsb, hex, rgb); 
        jQuery('#submenu_border_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit: navigation.setSubBorderColor 
    }).find('div').css('backgroundColor', navigation.getSubBorderColor());
    
    jQuery('#title_big_color').ColorPicker({  
      color: colorHelper.rgbToHex(jQuery('h1').css('color')), 
      onChange: function(hsb, hex, rgb) {
        jQuery('h1').css('color', '#' + hex);
        jQuery('#title_big_color div').css('backgroundColor', '#' + hex);
      }
    }).find('div').css('backgroundColor', colorHelper.rgbToHex(jQuery('h1').css('color')));
    
    jQuery('#title_medium_color').ColorPicker({  
      color: colorHelper.rgbToHex(jQuery('h2').css('color')), 
      onChange: function(hsb, hex, rgb) {
        jQuery('h2').css('color', '#' + hex);
        jQuery('#title_medium_color div').css('backgroundColor', '#' + hex);
      }
    }).find('div').css('backgroundColor', colorHelper.rgbToHex(jQuery('h2').css('color')));
    
    jQuery('#title_small_color').ColorPicker({  
      color: colorHelper.rgbToHex(jQuery('h3').css('color')), 
      onChange: function(hsb, hex, rgb) {
        jQuery('h3').css('color', '#' + hex);
        jQuery('#title_small_color div').css('backgroundColor', '#' + hex);
      }
    }).find('div').css('backgroundColor', colorHelper.rgbToHex(jQuery('h3').css('color')));
    
    
    jQuery('#links_color').ColorPicker({  
      color: colorHelper.rgbToHex(jQuery('h4 a').css('color')), 
      onChange: function(hsb, hex, rgb) {
        jQuery('.block a:not([class])').css('color', '#' + hex); // links in blocks
        jQuery('h4 a').css('color', '#' + hex); // the example
        jQuery('#footer .content a').css('color', '#' + hex); // links in the footer
        
        jQuery('#links_color div').css('backgroundColor', '#' + hex);
      }, 
      onSubmit: navigation.setSubTextColor 
    }).find('div').css('backgroundColor', colorHelper.rgbToHex(jQuery('h4 a').css('color')));
    
   
    
    // Fonts
    jQuery('#menu_font').bind('change', function(){
      jQuery('#menu_font').val();
      navigation.getMenuItems().css('fontFamily',jQuery('#menu_font').val() );
      navigation.getSubMenuItems().css('fontFamily',jQuery('#menu_font').val() );
    });
    jQuery('#menu_font').val(jQuery(navigation.getMenuItems()).css('fontFamily'));
    
    jQuery('#site_font').bind('change', function(){
      jQuery('#site_font').val();
      jQuery('#wrapper').css('fontFamily',jQuery('#site_font').val() );
    });
    jQuery('#site_font').val(jQuery("#wrapper").css('fontFamily'));
    
    jQuery('#title_font').bind('change', function(){
      jQuery('#title_font').val();
      jQuery('h1').css('fontFamily',jQuery('#title_font').val() );
      jQuery('h2').css('fontFamily',jQuery('#title_font').val() );
      jQuery('h3').css('fontFamily',jQuery('#title_font').val() );
      
    });
    jQuery('#title_font').val(jQuery("h1").css('fontFamily'));
    
    // themes
    jQuery('.themes a.theme').click(function(){
      return site.setTheme(jQuery(this).attr('href'));
    });
    
  },
  setThemeColors: function(color1, color2, color3, darkerColor1, darkerColor2) {
    jQuery('#menu_background_color').ColorPickerSetColor('#' + color1);
    jQuery('#menu_background_color div').css('backgroundColor', '#' + color1);
    navigation.setBackgroundColor(null, color1, null);

    jQuery('#menu_border_color').ColorPickerSetColor('#' + darkerColor1);
    jQuery('#menu_border_color div').css('backgroundColor', '#' + darkerColor1);
    navigation.setBorderColor(null, color1, null);

    jQuery('#menu_text_color').ColorPickerSetColor('#' + color3);
    jQuery('#menu_text_color div').css('backgroundColor', '#' + color3);
    navigation.setTextColor(null, color3, null);

    jQuery('#submenu_background_color').ColorPickerSetColor('#' + color2);
    jQuery('#submenu_background_color div').css('backgroundColor', '#' + color2);
    navigation.setSubBackgroundColor(null, color2, null);

    jQuery('#submenu_border_color').ColorPickerSetColor('#' + darkerColor2);
    jQuery('#submenu_border_color div').css('backgroundColor', '#' + darkerColor2);
    navigation.setSubBorderColor(null, color2, null);        

    jQuery('#submenu_text_color').ColorPickerSetColor('#' + color3);
    jQuery('#submenu_text_color div').css('backgroundColor', '#' + color3);
    navigation.getSubTextColor(null, color3, null);

    jQuery('#title_big_color').ColorPickerSetColor('#' + color2);
    jQuery('#title_big_color div').css('backgroundColor', '#' + color2);
    jQuery('h1').css('color', '#' + color2);

    jQuery('#title_medium_color').ColorPickerSetColor('#' + color2);
    jQuery('#title_medium_color div').css('backgroundColor', '#' + color2);
    jQuery('h2').css('color', '#' + color2);

    jQuery('#title_small_color').ColorPickerSetColor('#' + color2);
    jQuery('#title_small_color div').css('backgroundColor', '#' + color2);
    jQuery('h3').css('color', '#' + color2);
  },
  setTheme: function(theme) {
    switch(theme) {
      case "red":
        var color1 = '951c17';
        var color2 = 'cb1c17';
        var color3 = 'ffffff';
        var darkerColor1 = colorHelper.getDarkerShade(color1);
        var darkerColor2 = colorHelper.getDarkerShade(color2);
        
        this.setThemeColors(color1, color2, color3, darkerColor1, darkerColor2);
        break;
      case "blue":

        var color1 = '0053a4';
        var color2 = '008ae8';
        var color3 = 'ffffff';
        var darkerColor1 = colorHelper.getDarkerShade(color1);
        var darkerColor2 = colorHelper.getDarkerShade(color2);
        
        this.setThemeColors(color1, color2, color3, darkerColor1, darkerColor2);
        
        break;
      case "grey":
        var color1 = '3f3f3f';
        var color2 = '676767';
        var color3 = 'ffffff';
        var darkerColor1 = colorHelper.getDarkerShade(color1);
        var darkerColor2 = colorHelper.getDarkerShade(color2);
        
        this.setThemeColors(color1, color2, color3, darkerColor1, darkerColor2);
        
        break;
    }
    return false;
  },
  getStylesSetup: function() {
    var styles = [];
    
    styles['body'] = [];
    styles['body']['background-color'] = colorHelper.rgbToHex(jQuery('#background_color div').css('backgroundColor'));
    styles['body']['color'] = colorHelper.rgbToHex(jQuery('#text_color div').css('backgroundColor'));
    
    // p color same as body
    styles['p'] = [];
    styles['p']['color'] = styles['body']['color'];
    
    // border background color same as body but a bit darker
    styles['#footer .content'] = [];
    styles['#footer .content']['background-color'] = '#' + colorHelper.getDarkerShade(styles['body']['background-color'].substring(1));
    
    styles['#wrapper'] = [];
    styles['#wrapper']['font-family'] = jQuery('#site_font').val();
    
    styles['a'] = [];
    styles['a']['color'] = colorHelper.rgbToHex(jQuery('#links_color div').css('backgroundColor'));
    

    styles[navigation.menuItems] = [];
    styles[navigation.menuItems]['background-color'] = colorHelper.rgbToHex(jQuery('#menu_background_color div').css('backgroundColor'));
    styles[navigation.menuItems]['color'] = colorHelper.rgbToHex(jQuery('#menu_text_color div').css('backgroundColor'));
    styles[navigation.menuItems]['border-top-color'] = colorHelper.rgbToHex(jQuery('#menu_border_color div').css('backgroundColor'));
    styles[navigation.menuItems]['border-bottom-color'] = colorHelper.rgbToHex(jQuery('#menu_border_color div').css('backgroundColor'));
    styles[navigation.menuItems]['font-family'] = jQuery('#menu_font').val();
    
    // Footer menu color same as main navigation
    styles['#footermenu .content'] = [];
    styles['#footermenu .content']['background-color'] = styles[navigation.menuItems]['background-color'];
    styles['#footermenu .content ul li a'] = [];
    styles['#footermenu .content ul li a']['color'] = styles[navigation.menuItems]['color'];
    
    styles[navigation.subMenuItems] = [];
    styles[navigation.subMenuItems]['background-color'] = colorHelper.rgbToHex(jQuery('#submenu_background_color div').css('backgroundColor'));
    styles[navigation.subMenuItems]['color'] = colorHelper.rgbToHex(jQuery('#submenu_text_color div').css('backgroundColor'));
    styles[navigation.subMenuItems]['border-top-color'] = colorHelper.rgbToHex(jQuery('#submenu_border_color div').css('backgroundColor'));
    styles[navigation.subMenuItems]['border-bottom-color'] = colorHelper.rgbToHex(jQuery('#submenu_border_color div').css('backgroundColor'));
    styles[navigation.subMenuItems]['font-family'] = jQuery('#menu_font').val();
    
    styles['h1'] = [];
    styles['h1']['color'] = colorHelper.rgbToHex(jQuery('#title_big_color div').css('backgroundColor'));
    styles['h1']['font-family'] = jQuery('#title_font').val();
    
    styles['h2'] = [];
    styles['h2']['color'] = colorHelper.rgbToHex(jQuery('#title_medium_color div').css('backgroundColor'));
    styles['h2']['font-family'] = jQuery('#title_font').val();
    
    styles['h3'] = [];
    styles['h3']['color'] = colorHelper.rgbToHex(jQuery('#title_small_color div').css('backgroundColor'));
    styles['h3']['font-family'] = jQuery('#title_font').val();
    
    
    return styles;
    
  }
}

// Colorhelper
var colorHelper = {
  rgb:function(a){
    var o=a.toLowerCase();
    return[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4),16)];
  },
  shade:function(a,b){
    var v=[],i;
    for(i=0;i<3;i++){
      v[i]=Math.round(a[i]*b);
      if(v[i]>255)v[i]=255;
      if(v[i]<0)v[i]=0;
    }
    return v;
  },
  hex: function(a){
    var f=colorHelper._hex;
    return f(a[0])+f(a[1])+f(a[2]);
  },
  _hex: function(a){
    return ('0'+a.toString(16)).slice(-2);
  },
  getDarkerShade: function(color){
    var n,dark,lite;
    if(color.length<6){
      alert('Value must be a 6 character hex value.');
      return;
    }
    n=colorHelper.rgb(color);
    dark=colorHelper.hex(colorHelper.shade(n,0.9));
    return dark;
  },
  getLighterColor: function(color){
    var n,dark,lite;
    if(color.length<6){
      alert('Value must be a 6 character hex value.');
      return;
    }
    n=colorHelper.rgb(color);
    lite=colorHelper.hex(colorHelper.shade(n,1.2))
    return lite;
  },
  rgbToHex: function(rgb) { 
    if(rgb.length != 7){
      var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(rgb); 
      var rval = rgbvals[1]; 
      var gval = rgbvals[2]; 
      var bval = rgbvals[3]; 
      return '#' + 
        this.toHex(rval) + 
        this.toHex(gval) + 
        this.toHex(bval) 
      ;
    } else {
      return rgb;
    }
  },
  toHex: function(N) {
   if (N==null) return "00";
   N=parseInt(N); if (N==0 || isNaN(N)) return "00";
   N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
   return "0123456789ABCDEF".charAt((N-N%16)/16)
        + "0123456789ABCDEF".charAt(N%16);
  }
}

var jqmFunctions = {
  windowHeight: 0,
  
  rootUrl: jQuery('#root_url').attr('value'),

  init: function(rootUrl){
    this.rootUrl = rootUrl;
    // modal init
    jQuery('#jqModal').jqm({
      ajax:'@href',
      onLoad:jqmFunctions.jqmLoaded,
      onHide:jqmFunctions.close
    });
    
    jQuery(document).keydown( function( e ) {
      if( e.which == 27) {  // escape, close box
        jQuery(".jqmWindow").jqmHide();
      }
    });
    
    // jqm triggers
    jQuery('#newpage').click(function() {
      return jqmFunctions.jqmChangeClass(this, 'jqmNewPage');
    });

    jQuery('a.newitem').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmNewContainer');
    });

    jQuery('a.addMedia').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmNewContainer');
    });

    jQuery('a.addNews').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmTextEdit');
    });

    jQuery('a.addProject').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmTextEdit');
    });

    jQuery('a#edittitle').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmEdittitle');
    });
		
   	jQuery('div.widgetLinks a.edit').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmLinks');
    });
		
		jQuery('a.edit').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmTextEdit');
    });

    jQuery('a.addrow').live('click',function(){
      return jqmFunctions.jqmChangeClass(this, 'jqmNewRow');
    });
		
  },
  
  close: function(hash){
    hash.w.fadeOut('2000',function(){
      hash.o.remove();
      $(window).scrollTop(jqmFunctions.windowHeight);
    });
  },
  
  jqmLoaded: function(){
    jqmFunctions.windowHeight = $(window).scrollTop();
    window.scrollTo(0,0);
    
    var modal = jQuery('#jqModal');

    modal.addClass(modal.find('form').attr('class'));

    jQuery('textarea.wysiwyg').fck({ toolbar:'Custom', width: '897px' });
    jQuery("#uploadify").uploadify({
      'uploader'       : jqmFunctions.rootUrl + 'flash/uploadify.swf',
      'script'         : jqmFunctions.rootUrl + 'ajax/uploadimage',
      'cancelImg'      : jqmFunctions.rootUrl + 'images/cancel.png',
      'folder'         : '/uploads/' + jQuery('#site_upload_dir').attr('value'),
      'queueID'        : 'fileQueue',
      'auto'           : true,
      'multi'          : false,
      onComplete       : function(a, b, fileObj, response){     
        jQuery('.popupImage').html('Bestand uploaden voltooid');
        jQuery('#media_item_url').val('uploads/' + jQuery('#site_upload_dir').attr('value') + '/' + fileObj.name);
      },
      'onError'        : function(a, b, c, d){
        if (d.status == 404)
                    alert('Could not find upload script. Use a path relative to: '+'<?= getcwd() ?>');
                 else if (d.type === "HTTP")
                    alert('error '+d.type+": "+d.info);
                 else if (d.type ==="File Size")
                    alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
                 else
                    alert('error '+d.type+": "+d.info);
      }
    });
    jQuery('.jqmClose').click(function(){
      jQuery(".jqmWindow").jqmHide();
    })
        
    return false;
  },
  jqmChangeClass: function(element, classname) {
    jQuery('#jqModal').removeAttr('class');
    jQuery('#jqModal').addClass('jqmWindow');
    jQuery('#jqModal').addClass(classname);
    jQuery('#jqModal').jqmShow(element);
    return false;
  }
}

var news = {
  rootUrl: jQuery('#root_url').attr('value'),

  init: function(rootUrl) {
    this.rootUrl = rootUrl;
    // Confirm deletes
    jQuery('.newsItem .close').live('click', function(){

      var answer = confirm(jQuery.i18n._('delete_news'));
      if(!answer){
        return false;
      }
    });
    
    // New news form
    jQuery('#newNewsForm .newNewsForm').live('click',function(){
      jQuery.fck.update();
      jQuery('#newNewsForm').submit();
    });
    // Edit news form
    jQuery('#editNewsForm .editNewsForm').live('click',function(){
      jQuery('#editNewsForm').submit();
    });
  },
  loadNewValidation: function(){
    // New news form validation
    jQuery("#newNewsForm").validate({
      rules: {
        'news_item[title]': "required",
        'news_item[body]': "required"
      },
      messages: {
        'news_item[title]': jQuery.i18n._('news_title_validation_message'),
        'news_item[body]': jQuery.i18n._('news_body_validation_message')
      }
    });
  },
  loadEditValidation: function(){
    // New news form validation
    jQuery("#editNewsForm").validate({
      rules: {
        'news_item[title]': "required"
      },
      messages: {
        'news_item[title]': jQuery.i18n._('news_title_validation_message')
      }
    });
  }
}
var projects = {
  rootUrl: jQuery('#root_url').attr('value'),

  init: function(rootUrl) {
    this.rootUrl = rootUrl;
    // New project form
    jQuery('#newProjectForm .newProjectForm').live('click',function(){
      jQuery.fck.update();
      jQuery('#newProjectForm').submit();
    });
    // Edit project form
    jQuery('#editProjectForm .editProjectForm').live('click',function(){
      jQuery('#editProjectForm').submit();
    });
    
  },
  loadNewValidation: function(){
    // New news form validation
    jQuery("#newProjectForm").validate({
      rules: {
        'project[title]': "required",
        'project[body]': "required"
      },
      messages: {
        'project[title]': jQuery.i18n._('project_title_validation_message'),
        'project[body]': jQuery.i18n._('project_body_validation_message')
      }
    });
  },
  loadEditValidation: function(){
    // New news form validation
    jQuery("#editProjectForm").validate({
      rules: {
        'project[title]': "required"
      },
      messages: {
        'project[title]': jQuery.i18n._('project_title_validation_message')
      }
    });
  }
}
var page = {
  rootUrl: jQuery('#root_url').attr('value'),

  init: function(rootUrl) {
    this.rootUrl = rootUrl;
    // Choose page type and fill in hidden field
    jQuery('#newPageForm .btn2').live('click',function(){
      // update widget_type
      var type_id = jQuery(this).attr('href');
      jQuery('#page_page_type_id').val(type_id);

      jQuery('#newPageForm .btn2').each(function(){
        jQuery(this).removeClass('active');
      });
      jQuery(this).addClass('active');
      jQuery('#formWrapper').show();
      
      jQuery('#save').show();
      jQuery('#close').show();

      return false;
    });


    // Save page form
    jQuery('#newPageForm #save').live('click',function(){
      jQuery('#newPageForm').submit();
    });

    // Edit title form
    jQuery('#editPageForm #save').live('click',function(){
      jQuery('#editPageForm').submit();
    });
    
    // Image resize if to big
    this.fixImageWidths();
  },
  fixImageWidths: function() {
    jQuery('.block img').each(function() {
      var img = jQuery(this);
      var width = img.parent().width();
      if ((img.width()) > width) {
        img.width(width);
      }
    });
  },
  loadNewValidation: function(){
    // New news form validation
    jQuery("#newPageForm").validate({
      rules: {
        'page[title]': "required"
      },
      messages: {
        'page[title]': jQuery.i18n._('page_title_validation_message')
      }
    });
  },
  loadEditValidation: function(){
    // New news form validation
    jQuery("#editPageForm").validate({
      rules: {
        'page[title]': "required"
      },
      messages: {
        'page[title]': jQuery.i18n._('page_title_validation_message')
      }
    });
  }
}

var media = {
  rootUrl: jQuery('#root_url').attr('value'),

  init: function(rootUrl) {
    this.rootUrl = rootUrl;
    // Choose media type and fill in hidden field
    jQuery('#newMediaForm .btn2').live('click',function(){
        // update widget_type
      var type_id = jQuery(this).attr('rel');
      jQuery('#page_page_type_id').val(type_id);
      if (type_id == 'video') {
        jQuery('.popupImage').hide();
        jQuery('.popupVideo').show();
      } else {
        jQuery('.popupVideo').hide();
        jQuery('.popupImage').show();
      }
      jQuery('#newMediaForm .btn2').each(function(){
        jQuery(this).removeClass('active');
      });
      jQuery(this).addClass('active');
      jQuery('#formWrapper').show();
      jQuery('#save').show();
      jQuery('#close').show();
      
      return false;
    });


    // Save media form
    jQuery('#newMediaForm #save').live('click',function(){
        jQuery('#newMediaForm').submit();
    });
  },
  loadNewValidation: function(){
    // New news form validation
    jQuery("#newMediaForm").validate({
      rules: {
        'media_item[title]': "required"
      },
      messages: {
        'media_item[title]': jQuery.i18n._('media_title_validation_message')
      }
    });
  },
  loadEditValidation: function(){
    // New news form validation
    jQuery("#editMediaForm").validate({
      rules: {
        'media_item[title]': "required"
      },
      messages: {
        'media_item[title]': jQuery.i18n._('media_title_validation_message')
      }
    });
  }
}

jQuery().ready(function(){
  // Root url of the site
  var rootUrl = jQuery('#root_url').attr('value');
  
  // FCKEditor config
  jQuery.fck.config = {path: rootUrl + 'fckeditor/', height:300 };
  
  // New ajax queue manager, clears the queue when adding a new request;
  var ajaxManager = jQuery.manageAjax.create('ajaxQueue', { queue: 'clear' });
  
  // Init
  customLayout.init(rootUrl, ajaxManager);
  navigation.init(rootUrl, ajaxManager);
  jqmFunctions.init(rootUrl);
  widget.init(rootUrl);
  news.init(rootUrl);
  projects.init(rootUrl);
  page.init(rootUrl);
  media.init(rootUrl);
  
});

