// helper functions
String.prototype.trim = function(){return(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));};
String.prototype.startsWith = function(str){return (this.match("^"+str)==str);};
String.prototype.endsWith = function(str){return (this.match(str+"$")==str);};

// Arcadia Portfolios class 
AP = window.AP || {};

AP.CSS = {
  appendCss: function(css, id, doc) {
		if(!doc) {
			doc = document;
		}
		
		var head = $(doc).find('head')[0];
		
		if(id) {
			$(doc).find('#'+id).each(function(){
				$(this).remove();
			});
		}
		
		var styleText = '<style type="text/css"' + (id ? 'id="'+id+'"' : '') + '>';
		styleText = styleText + css;
		styleText = styleText + '</style>';
		
		$(head).append(styleText);
	},
	
	reload: function(doc) {
	  if(!doc) {
	    doc = document;
	  }

	  var style = $(doc).find('#mainstylesheet');  
	  var url = '/display/main.css?id=' + parseInt(Math.random() * 99999999);

	  style.attr('href', url);
	}
};

AP.Management = {
 
  toggleMenu: function() {
    if($('#management-strip').is(':hidden')) {
      $('#managementLink-configure').css('background', '#202020');
      $('#management-strip').animate({
        height: 'show',
        opacity: 'show'
      }, 'fast');
    }
    else {
      $('#managementLink-configure').css('background', '#353535');
      $('#management-strip').animate({
        height: 'hide',
        opacity: 'hide'
      }, 'fast');
    }
  },  
  
  logoutAnimate: function(url, callback) {
  	$('body').animate({
  		paddingTop: "0px",
  		queue: false
  	}, 1000);
  	$('#managementbar').hide("slide", {direction: "up"}, 1000);
//  	$('#appearance-container').hide("slide", {direction: "down"}, 1000);
  	
    AP.URL.call(url, callback);
  },

  selectTab: function(type) {
    AP.Management.setTab(type);
    AP.Management.toggleMenu();
  },
  
  setTab: function(type) {
    var container = '#' + type + '-container';
    $('#canvasWrapper').animate({
      paddingBottom: '335px',
      queue: false
    }, 'fast');
    $(container).show();
  },  
  
  hideEditor: function() {
    if(!$('#editor-container').is(':hidden')) {
      $('#layout-container .selected').removeClass('selected');
      $('#editor-container').animate({
        height: 'hide',
        opacity: 'hide',
        queue: false
      }, 'fast');
      $('#canvasWrapper').animate({
        paddingBottom: '0px',
        queue: false
      }, 'fast');
      $('#layout-container').animate({
        height: 'hide',
        opacity: 'hide'
      }, 'fast');
      
    }
  },
  
  toggleEditor: function(editor, p) {
  	var url = base_url + 'display/Admin/Editor' + editor;
  	  	  	
  	if($('#editor-container').is(':hidden')) {
  		// show editor
  		$('#editor-container').animate({
  			height: 'show',
  			opacity: 'show'
  		}, 'fast');
  		
  		$('#editor-container-frame').attr('src', url);
  		$(p).addClass('selected');
  	}
  	else
  	{		
  		// visible, so hide if selected
  		if($(p).hasClass('selected'))
  		{
  			$(p).removeClass('selected');
  			$('#editor-container').animate({
  				height: 'hide',
  				opacity: 'hide'
  			}, 'fast');			
  		}
  		else
  		{
  			$('#layout-container .selected').removeClass('selected');
  			$(p).addClass('selected');
  			$('#editor-container-frame').attr('src', url);
  		}
  	}
  }
  
};

AP.URL = {
  call: function(Url, callback){
    jQuery.ajax({
      type: "POST",
      url: Url,
      timeout: 10000,
      success: callback ? callback : function(data, status){},
      error: function(XMLHttpRequest, textStatus, errorThrown){
        alert("No Save Warning");
      }
    });
  }
};

AP.Editor = {
  current: null,
  
  setCurrent: function(type) {
    $('#editor-content').empty();
    
    if(AP.Editor.callbacks[type])
      AP.Editor.callbacks[type].start();
    
    AP.Editor.current = type;
  },
  
  show: function() {
    $('#editor-container').animate({
      height: 'show',
      opacity: 'show'
    }, 'fast');    
  },
  
  hide: function() {
    $('#editor-container').animate({
      height: 'hide',
      opacity: 'hide'
    }, 'fast');     
  },
   
	edit: function(type, element) {
    
    if(AP.Editor.current && AP.Editor.callbacks[AP.Editor.current])
      AP.Editor.callbacks[AP.Editor.current].stop();
       
    if($('#editor-container').is(':hidden')) {
      // show editor
      if(AP.Editor.current != type) {
        $('#editor-content').empty();
      }
      
      AP.Editor.show();

      $(element).addClass('selected');
      AP.Editor.setCurrent(type);
    }
    else
    {   
      $('#layout-container .selected').removeClass('selected');
      
      // visible, so hide if selected
      if(AP.Editor.current == type)
      {
        AP.Editor.hide();
        return;
      }
      else
      {
        $(element).addClass('selected');
        AP.Editor.setCurrent(type);
      }
    }   
	},

  callbacks: {
	  Templates: {
	    start: function() {},
	    stop: function() {}
	  },
	  
	  Layout: {
	    start: function() {
	      var url = base_url + 'display/Admin/EditorLayout';
	      $('#editor-content').append('<iframe id="appearance-container-frame" src="'+url+'" width="100%" height="100%" frameborder="0"></iframe>');
	    },
	    stop: function() {}
	  },
	  
    Menu: {
      start: function() {
        var url = base_url + 'display/Admin/EditorMenu';
        $('#editor-content').load(url, function(){
            
          // insert empty containers, making them no draggable
          $('.content-navigation').each(function(i, e){
            if($(e).find('li').size() == 0) {
              $(e).append('<li class="empty_holder"><div>Drag Item Here</div></li>');
            }
          });
      
          $('.content-navigation').sortable({
            connectWith: '.content-navigation',
            distance: 5,
            items: 'li.module',
            start: function() { $('.content-navigation a').click(function() { return false; })},
            stop: function() { setTimeout("$('.content-navigation a').unbind('click')", 10);},
            update: function(event, ui) {
              var d = {};
              var i = 0;
          
              var id = $(this).parent().parent().attr('id');
          
              var count = $(this).find('li').size();
              var empty = $(this).find('li.empty_holder');
            
              if(count > 1 && empty != null) {
                // remove empty
                $(empty).remove();
              } else if(count == 0) {
                $(this).append('<li class="empty_holder"><div>Drag Item Here</div></li>');
              }
            
              d.links = $(this).sortable('serialize');
              d.navbar = id;
          
              jQuery.ajax({
                type: "POST",
                data: d,
                url: base_url+'process/MenuEdit',
                timeout: 10000,
                success: function(data, status){},
                error: function(XMLHttpRequest, textStatus, errorThrown){
                  alert("No Edit Warning");
                }
              });
            }
          });
        });
      },
      
      stop: function() {
        $('.content-navigation').sortable('destroy');
        $('.content-navigation li.empty_holder').remove();        
      }
    },
    
    Colours: {
      start: function() {
        var url = base_url + 'display/Admin/EditorColours';
        $('#editor-content').append('<iframe id="appearance-container-frame" src="'+url+'" width="100%" height="100%" frameborder="0"></iframe>');
      },
      stop: function() {
      }
    },
    
    CustomCSS: {
      start: function() {
        var url = base_url + 'display/Admin/EditorCustomCSS';
        $('#editor-content').append('<iframe id="appearance-container-frame" src="'+url+'" width="100%" height="100%" frameborder="0"></iframe>');
      },
      stop: function() {}  
	  },
	  
    Advanced: {
      start: function() {
      },
      stop: function() {}
    }
  }
}

AP.Debug = {
  dump: function(arr, level) {
    var dumped_text = "";
    if(!level) level = 0;

    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    if(typeof(arr) == 'object') { //Array/Hashes/Objects 
      for(var item in arr) {
        var value = arr[item];
      
        if(typeof(value) == 'object') { //If it is an array,
          dumped_text += level_padding + "'" + item + "' ...\n";
          dumped_text += dump(value,level+1);
        } else {
          dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
      }
    } else { //Stings/Chars/Numbers etc.
      dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
  }
};

AP.Form = {
  enableButton: function(id, text) {
    // remove button-disabled and add button to id
    // change text of button (span element)
    $(id).addClass('button');
    $(id).removeClass('button-disabled');
    $(id).find('span').each(function(){$(this).text(text);});
  },
  
  disableButton: function(id, text) {
    $(id).addClass('button-disabled');
    $(id).removeClass('button');
    $(id).find('span').each(function(){$(this).text(text);});    
  },
  
  isButtonDisabled: function(id) {
    return $(id).hasClass('button-disabled');
  },
  
  isButton: function(id) {
    return $(id).hasClass('button-disabled') || $(id).hasClass('button');
  },

  isButtonEnabled: function(id) {
    return $(id).hasClass('button');
  }
};
