/*
  Camargue JS API
  Date: 2009-09-04
  Version: 0.1.0
  Revision: 6246
  Provides core funcionality for CMS GUI etc.
  Requires jQuery 1.3, http://jquery.com/
  Requires jQuery.create(), http://blogs.microsoft.co.il/blogs/basil/archive/2008/08/21/jquery-create-jquery-plug-in-to-create-elements.aspx
 */

var Camargue = {
  // private/ config
  _required_js: ['jquery-impromptu.2.7.js' // Impromptu, Camargue.Dialog + Camargue.Modal
             ,'jquery-create.js', // jQuery.create(), shared - http://blogs.microsoft.co.il/blogs/basil/archive/2008/08/21/jquery-create-jquery-plug-in-to-create-elements.aspx
             'jquery-ui-1.7.2.custom.min.js' // jQuery UI (no widgets required) - http://jqueryui.com/
             ,'jquery.notice.js' // growl, http://code.google.com/p/jquery-notice/
             ,'jquery.blockUI.js' // jQuery BlockUI Plugin (v2), http://malsup.com/jquery/block/
             ,'FANCY_VIEWER/fv-0.3.6/js/FancyViewer.js'
             // ,'json.js'
             ],
  _required_css: [// 'FANCY_VIEWER/fv-0.3.6/css/fancyviewer.css'
  							],
  _pluginFolder: '/required',
  
  ///////////////////////// Properties //////////////////////////////
  VERSION: '0.3.0',
  SCRIPT_URL: '',
  BASEURL: '',
  BASEDIR: '',
  modals: new Array(),
  tooltips: new Array(),
  notices: new Array(),  
  
  ///////////////////////// Functions /////////////////////////////// 
  // init
  init: function() {
  	// alert('start init');
    // get path
    $('script').map(function(i) { 
      if (this.src.match(/Camargue\.js(\?.*)?$/)) {
        Camargue.SCRIPT_URL = this.src.replace(/\/Camargue\.js(\?.*)?$/, '');
      }
    });  
    
    // insert required scripts
	/*
    Camargue._required_js.map(function(script) {
      var script = Camargue.SCRIPT_URL + Camargue._pluginFolder + '/' + script;
      $('head').append('<script type="text/javascript" src="' + script + '"></script>');
    }); 
	*/
    
    // insert required CSS
    /*
	Camargue._required_css.map(function(script) {
      var script = Camargue.SCRIPT_URL + Camargue._pluginFolder + '/' + script;
      $('head').append('<link rel="stylesheet" type="text/css" href="' + script + '">');      
    });
	*/     
    
    /*
    // apply ballons for editing
    var numModules = 0;
    var hideTimeout = null;
    $("*[rel*='sancho|']").each(function(i) {
      numModules++;
      // $(this).css('border', '1px solid red');
  		var vals = $(this).attr('rel').split('|');
      // sancho|man_menu_manager|1|params
      var moduleName = vals[1];
      var moduleContentId = vals[2];
      var moduleParams = vals[3];
      var pageArea = $(this).parent().attr('id');
    	// alert('Module found: ' + moduleName + '/' + moduleContentId + '/' + moduleParams);
      
      // do stuff      
      var $cur = $(this); // fix scope      
			$.getJSON(Camargue.SCRIPT_URL + '/get_module_data.php?module_name=' + moduleName,
        function(data){
        	var mod = new Array();
          $.each(data, function(i,item){
          	mod[i] = item;
          });
          
          $cur.unbind('mouseenter');
          $cur.unbind('mouseleave');                                                
        	$cur.bind('mouseenter', function(e) {          	
            $("*[rel*='sancho|']").css('outline', 'none');// reset all leftover outlines 
          	Camargue.Tooltip.hide(); 
            Camargue.Tooltip.keepVisible = true;                        	               
						$(e.currentTarget).css('outline', '2px dotted #ddd');      					            
            Camargue.Tooltip.empty();        
            var params = 'page_id=1&page_area=' + pageArea + '&page_content_id=&module_id=' + mod.id + '&module_data=' + moduleContentId;
        		if (mod.fileEdit) Camargue.Tooltip.addLink(mod.directory + '/' + mod.fileEdit + '?' + params, 'Edit ' + mod.button.toLowerCase(), 'edit', mod.fileEditModalWidth, mod.fileEditModalHeight);    
            if (mod.fileRemove) Camargue.Tooltip.addLink(mod.directory + '/' + mod.fileRemove + '?' + params, 'Delete ' + mod.button.toLowerCase(), 'delete', mod.fileRemoveModalWidth, mod.fileRemoveModalHeight); 
            if (mod.fileInsert) Camargue.Tooltip.addLink(mod.directory + '/' + mod.fileInsert + '?' + params, 'Add ' + mod.button.toLowerCase(), 'add', mod.fileInsertModalWidth, mod.fileInsertModalHeight);              
          	Camargue.Tooltip.show(e);
          	e.stopPropagation();               
          });
          $cur.bind('mouseleave', function(e) { 
          	Camargue.Tooltip.keepVisible = false; 
 						setTimeout(function () { 
            	if (!Camargue.Tooltip.keepVisible ) {        
    						$(e.currentTarget).css('outline', 'none');           
              	Camargue.Tooltip.hide();
            		$("*[rel*='sancho|']").css('outline', 'none'); // reset all leftover outlines                 
              } 
            }, 2500);             	
            e.stopPropagation();                    
          });
          
          $('#camargue_tooltip').unbind('mouseenter');   
          $('#camargue_tooltip').unbind('mouseleave');
        	$('#camargue_tooltip').bind('mouseenter', function(e) {                     
          	Camargue.Tooltip.keepVisible = true;                       
          });
          $('#camargue_tooltip').bind('mouseleave', function(e) {
          	Camargue.Tooltip.keepVisible = false; 
            setTimeout(function () { 
            	if (!Camargue.Tooltip.keepVisible) {            
    						$(e.currentTarget).css('outline', 'none');           
              	Camargue.Tooltip.hide();
            		$("*[rel*='sancho|']").css('outline', 'none'); // reset all leftover outlines                 
              } 
            }, 2500);                    
          });          
          
			});
    });
    // alert(numModules + ' modules processed');
   */
  },

  
  // updates a node by refreshing the page with Ajax 
  refreshNode: function(expr, url, onUpdate) {
  	url = new String(url).replace('#', ''); // make sure url doesn't contain anchor or it won't refresh
    //alert(expr);
    var outdatedNode = $(expr);
    //alert(outdatedNode.html());
    // alert('outdated node length: ' + outdatedNode.length);
    var temp_div_id = 'camargue_refresh_node_' + Math.floor(Math.random()*100);
    var elem = $(expr);
	elem.block({
		message: '<span style="color:#fff;font:11px \'Trebuchet MS\';word-wrap:break-word;line-height:16px;"><img src="/CAMARGUE/images/loader.gif" style="display:inline;border:0px;">&nbsp;&nbsp;&nbsp;refreshing&nbsp;area</span>',
		baseZ: 9998,
		css: { 
			color:          '#fff', 
			width:          '80%', 
			border:         '0px solid #aaa', 
			backgroundColor:'transparent', 
			cursor:         'wait' 
			}
	});
             
    $.get(url, function(data) {  
        $('body').append('<div id="' + temp_div_id + '" style="display: none;"></div>');
        $('#' + temp_div_id)[0].innerHTML = data;
        // alert($('#' + temp_div_id));
        var newNode = $('#' + temp_div_id).find(expr);
        // alert('exp: ' + expr + ', new node: ' + newNode.length);
        if (newNode.html()) {
        	// alert(newNode.html());
          outdatedNode.replaceWith(newNode);
          $(elem).unblock();
          //$(newNode).effect("pulsate", { times:2 }, 500);        
        } else {
          $(elem).unblock();
          //$(outdatedNode).effect('puff', {}, 1000);
        }   
        // alert('eval');  
        eval(onUpdate);
        $('#' + temp_div_id).remove();
        return;
    }); 
  },
  
  block: function(elem, msg) {
  	$(elem).block({ 
                	message: msg,
                  css: { 
                        padding:        0, 
                        margin:         0, 
                        width:          'auto',
                        paddingLeft:    '35px', 
                        height:         '35px',
                        top:            '40%', 
                        left:           '35%', 
                        textAlign:      'center', 
                        lineHeight:     '35px',
                        color:          '#222', 
                        border:         '0', 
                        backgroundColor:'transparent', 
                        cursor:         'wait',
                        backgroundImage: 'url(' + Camargue.SCRIPT_URL + '/images/wait-loader-big.gif)',
                        backgroundRepeat: 'no-repeat',
                        fontSize:        '12px'
                        },
                  overlayCSS:  { 
                        backgroundColor: '#fff', 
                        opacity:         0.8 
    										}
                	});
    
  },
  
  release: function(elem) {
  	$(elem).unblock();
  },
  
  ///////////////////////// Objects /////////////////////////////////
  
  ///// Tooltip /////
  Tooltip: {
  	keepVisible: false,
    isBeingShown: false,
    
  	init: function() {
    	// alert('init tooltip');
      var html = '';
      html += '<div id="camargue_tooltip" class="tooltip">';
      html += '<div class="body">';
      /*
      <a href="#" class="tools">propriet� pagina</a>
      <a href="#" class="puzzle">aggiungi modulo</a>
      <a href="#" class="accept">attiva pagina</a>
      <a href="#" class="remove">sospendi pagina</a>
      <a href="#" class="trash">elimina pagina</a>
      <a href="#" class="lock">blocca pagina</a>
      <a href="#" class="unlock">sblocca pagina</a>
      */
      html += '</div>';
      html += '<div class="bottom"></div>';
      html += '</div>';
      $('body').append(html);      
    },
       
		show: function(e) {
    	// alert(e.currentTarget.innerHTML);
    	if (!$('#camargue_tooltip').length) {
				Camargue.Tooltip.init();
      }
      
      var isXLeft = 0;
      var isXMiddle = 0;
      var isYTop = 0;
      var isYBottom = 0;
      
      var offsetLeft;
      if ($(e.currentTarget).outerWidth() > $('#camargue_tooltip').outerWidth()) {
      	isXLeft = 1;
      	offsetLeft = $(e.currentTarget).offset().left;
      } else {
      	isXMiddle = 1;
      	offsetLeft = $(e.currentTarget).offset().left + $(e.currentTarget).outerWidth()/2 - $('#camargue_tooltip').outerWidth()/2  // e.pageX - $('#camargue_tooltip').outerWidth()/2;
      }
      var offsetTop;     
      if ($(e.currentTarget).offset().top - $(window).scrollTop() > $('#camargue_tooltip').outerHeight()) {
      	// place on top
        isYTop = 1;
        offsetTop = $(e.currentTarget).offset().top - $('#camargue_tooltip').outerHeight();
      } else {
      	// place at top
        isYBottom = 1;
        offsetTop = $(e.currentTarget).offset().top + $(e.currentTarget).outerHeight();      
      }
      
      // place stem
      var oClass = 'tooltip stem';
      if (isYTop) oClass += '_bottom';
      if (isYBottom) oClass += '_top';
      if (isXLeft) oClass += '_left';
      if (isXMiddle) oClass += '_middle';      
      
      $('#camargue_tooltip').attr('class', oClass);
      $('#camargue_tooltip').css('left', offsetLeft + 'px');      
      $('#camargue_tooltip').css('top', offsetTop + 'px'); 
      $('#camargue_tooltip').fadeIn('slow');
    },
    
    hide: function() {
      $('#camargue_tooltip').hide();
    },
    
    addBlockTitle: function(text) {
    	$('#camargue_tooltip div.body').append('<span>' + text + '</span>');
    },
    
    addSeparator: function() {
    	$('#camargue_tooltip div.body').append('<hr>');
    },
    
    addLink: function(txt, href, descr, options) {
    	if (!options) options = {};
    	if (!$('#camargue_tooltip').length) {
				Camargue.Tooltip.init();
      }    
    	$('#camargue_tooltip div.body').append('<a href="#" class="' + options.type + '">' + txt + '</a>');
      $('#camargue_tooltip div.body a:last').click(function() {
      	if (typeof href == 'string') {
   				var fv = new FancyViewer({theme: 'camargue'});
          fv.addToSet(href, txt, descr, {width: options.modalWidth, height: options.modalHeight});
          fv.open(0);
          Camargue.modals[options.modalName] = fv;
        } 
        Camargue.Tooltip.hide();
        return false;
      });
    },
    empty: function() {
    	if (!$('#camargue_tooltip').length) {
				Camargue.Tooltip.init();
      }    
    	$('#camargue_tooltip div.body')[0].innerHTML = '';
    }
  },
  
  ///// Dialog /////
  /* 
    based on jQuery Impromptu, http://trentrichardson.com/Impromptu/
    options:
    type > alert|confirm|prompt
    submit
    callback
  */
  Dialog: {
    open: function(message, options) {
      var myMessage = message;
      var myButtons = '';
      
      // change layout according to dialog type
      switch (options.type) {  
        case 'alert':
          myButtons = {'Ok': 1, 'Cancel': 0};
          break;    
        case 'prompt':  
          // add input field
          myMessage += '<br><input type="text" id="input" name="input">';               
          myButtons = {'Ok': 1, 'Cancel': 1};
          break;
        case 'confirm':       
          myButtons = {'Ok': 1, 'Cancel': 1};
          break;  
      }
      $.prompt(myMessage, {
                buttons: myButtons,
                submit: function() {},
                callback: function() {}
                });      
      return;    
    } 
  },
  
  ///// Modal /////
  /* 
    based on jQuery Impromptu, http://trentrichardson.com/Impromptu/
  */
  
  Modal: {
    open: function(url, name, options) { 
      if (!name) return 0;      
      var minWidth = 500;
      var minHeight = 400;     
      var iframeWidth = options.width ? options.width : minWidth;
      var iframeHeight = options.height ? options.height : minHeight;      
      var iframe =  '<iframe style="border: 0; width: ' + iframeWidth + 'px; height: ' + iframeHeight + 'px;" border="0" frameborder="0" src="' + url + '"></iframe>'; 

      var myPrompt = $.prompt(iframe, {
                buttons: {},
                submit: function() {},
                callback: function() {}
                });  
      return myPrompt;                         
    },
    
    resizeX: function(newSize) {
      var promptNode = $('#jqi')[0];
      var promptFrame = $('.jqimessage > iframe')[0]; 
      // animate frame
      $(promptFrame).animate({width: newSize}, 1000);      
      // animate box    
      var posX = ($(window).width() - newSize)/2 + 'px';
      var boxWidth = newSize + (promptNode.style.paddingLeft + promptNode.style.paddingRight)*2 + 'px';
      $(promptNode).animate({width: boxWidth, marginLeft: 0, left: posX}, 600);  
    },
    
    resizeY: function(newSize) {
      var promptNode = $('#jqi')[0];
      var promptFrame = $('.jqimessage > iframe')[0];  
      // animate frame
      $(promptFrame).animate({height: newSize}, 600);
      // animate box                   
      var posY = ($(window).height() - newSize)/2 + 'px';
      var boxHeight = newSize + (promptNode.style.paddingTop + promptNode.style.paddingBottom)*2 + 'px';      
      $(promptNode).animate({height: boxHeight + promptNode.style.paddingTop + promptNode.style.paddingBottom, marginTop: 0, top: posY}, 1000);   
    },
    
    resize: function(sizeX, sizeY) {
      var promptNode = $('#jqi')[0];
      var promptFrame = $('.jqimessage > iframe')[0]; 
      // animate frame
      $(promptFrame).animate({width: sizeX, height: sizeY}, 600);      
      // animate box    
      var posX = ($(window).width() - sizeX)/2 + 'px';
      var posY = ($(window).height() - sizeY)/2 + 'px';      
      var boxWidth = sizeX + (promptNode.style.paddingLeft + promptNode.style.paddingRight)*2 + 'px';
      var boxHeight = sizeY + (promptNode.style.paddingTop + promptNode.style.paddingBottom)*2 + 'px';      
      $(promptNode).animate({width: boxWidth, height: boxHeight, marginLeft: 0, marginTop: 0, left: posX, top: posY}, 600);          
    },
        
    close: function() {} 
  },  
  
  ///////////////////////// Helper functions /////////////////////////////////
  
  /*
  showControls: function() {
  	alert('show controls');
		$('head').append('<link rel="stylesheet" href="' + Camargue.SCRIPT_URL + '/css/controls.css" type="text/css">');
  },
  */
  
  // opens a modal window. adds name to CMS.modals. returns CSM.Modal object
  open: function(url, name, options) {
    Camargue.Modal.open(url, name, options);
  },
  
  // loads a full page
  iframeGo: function (url) {
  $('#camargue_main_iframe').attr('src', url);
    $('#camargue_main_iframe_wrapper').show('blind');
  },
  
  // hides iframe
  iframeClose: function () {
    $('#camargue_main_iframe_wrapper').hide('blind');
  },
  
  // returns CMS.Dialog, hides all other alerts
  alert: function(message) {
    Camargue.Dialog.open(message, {type: 'alert'});  
  },
  
  // returns CMS.Dialog, hides all other alerts  
  prompt: function(message) {
    Camargue.Dialog.open(message, {type: 'prompt'});
  },
  
  // returns CMS.Dialog, hides all other alerts
  confirm : function(message) {
    Camargue.Dialog.open(message, {type: 'confirm'});  
  },

  // updates any element on the page without specific Ajax functions
  updateElement: function(elem, url) {
  },
  // shows a notification, color-codes are 'success', 'problem', 'error', 'general'
  noticeAdd: function(message, infoType, noticeName) {
  },
  // shows a notification, color-codes are ok, info, error. Adds to CMS.notices
  noticeRemove: function(myNotice) {
  }, 

  // highlights an element (to be edited/deleted or moved)
  highlight: function(elem) {
  }
};

$(document).ready(function() {
	Camargue.init();
});

