/**
 * Artibox JS Class
 * 
 * This file contains all the method for the artibox uses.
 * This file use and require jquery and jquery-ui dialog plugin  
 * 
 * @author fl0r3nt
 */

if (artilinki == undefined) {
	var artilinki;
}
	
function Artibox(v_container) {
  this._container       = v_container;
  this._content         = '';
  this._name            = '';
  this._title           = '';
  this._link            = null;
  this.liveClickId      = null;
  this._links           = this._loadedContent = [];
  this._offset          = 0;
  this._type 			= 'iframe';
  this.options			= {
	isSecure 		: false,
	isLogin 		: false,
	hasNoCache 		: false,
	isWhiteClass 	: false,
	hasNoPadding 	: false,
	ajaxCallback 	: null,
	dialogClass		: '',
	secure_url		: artilinki != undefined ? artilinki.options.lightbox.secure_access_url:''
  };
  
  /**
   * init
   * instantiate the artibox.
   * Adding a div element to body if necessary
   * @author fl0r3nt
   */
  Artibox.prototype.init=function() {
    if (typeof(this._container) == 'undefined' || this._container == null) {
      $('body').after('<div class="nopadding" id="artibox" style="display: none"></div>');
      this._container = $('#artibox');
    }
  };
  
  /**
   * scanLinks
   * add onClick event listener on all link width 'artibox' class
   * @author fl0r3nt
   */
  Artibox.prototype.scanLinks = function(elem, nocache) {
	var elems = elem != null ? $(elem).find("a.artibox") : $("a.artibox");
	elems.each(function(i, elt){
	  $(elt).bind('click', function(event) {
		event.preventDefault();
		artibox.open(event.currentTarget, i, nocache);
	  });
	});
  };
  
  /**
   * unbindLinks
   * remove onClick event listener on all link width 'artibox' class
   * @author fl0r3nt
   */
  Artibox.prototype.unbindLinks = function(elem) {
	var elems = elem != null ? $(elem).find("a.artibox") : $("a.artibox");
	elems.each(function(i, elt){
	  $(elt).unbind('click');
	});
  };

  /**
   * open
   * open the right dialog in the right context
   * @author fl0r3nt
   */
  Artibox.prototype.open = function(element, v_offset, nocache) {
	this.init();
	if (this._links[v_offset] != null && nocache != true) {
      this._link = this._links[v_offset];
    }
    else {
      this._link = $(element);
    }
	if (this._link.hasClass('livelink') && this.liveClickId != this._link.attr('id')) {
		this.liveClickId = this._link.attr('id');
		return false;
	} 
	else if (this.liveClickId != this._link.attr('id')) {
    	this.liveClickId = null;
    }
	
	// Get default options
	this.getOptionsFromClassNames();
    this.setName();   
    //Getting type of the box (iframe, div, ajax, ...)
    this._type = this._link.attr('rel');
    this._links[v_offset] = this._link;
    
    //Creating dialog box
    if(this._container.dialog) this._container.dialog('destroy');
    this._container.dialog({
      modal: true,
      draggable : false,
      autoOpen: false, 
      resizable: true
    });
   
    //gets box content
    this.getContent();   
    //Resizing box container and setting up dialog options
    this.setOptions();        
    //sets up events listeners
    this._container.bind('dialogopen', this.showOverlay);
    this._container.bind('dialogclose', this.emptyContainer);
    //open box
    this._container.dialog("open");
  };
    
  /**
   * getContent
   * create container and retrieve content considering the rel type
   * @author fl0r3nt
   */
  Artibox.prototype.getContent=function() {
	  var id = this._link.attr('id');
	  switch (this._type) {
      	case 'iframe':
    	  var autoscroll = this._link.hasClass('autoscroll') ? 'auto':'no';
    	  this._container.html("<iframe id='artibox_iframe' scrolling='"+autoscroll+"' width='"+this.options.width+"' height='"+(this.options.height-28)+"' name='iframe_"+new Date().getTime()+"' frameborder=0 src='"+this.getIframeUrl()+"' allowtransparency='true'/>");
    	  this.showLoading();
    	break;
      	case 'div':
    	  this._content = $('#artibox_'+id);
    	  this._container.html(this._content.html());
    	  this.setupLoadingElements();
    	break;
      	case 'ajax':
    	  this._container.html('&nbsp;');
    	  if (this._loadedContent[this._link.name] != null) {
    	    this._container.html(this._loadedContent[this._link.name]);
    	    artibox.initAjaxForm();
    	    if(artibox.options.ajaxCallback != null) { 
	    	  eval(artibox.options.ajaxCallback+'();');
	        }
    	  }
    	  else {
    	  	if (this.options.isSecure) {
	    	  this._container.load(this.options.secure_url+this.getSequenceIdFromElementId(this._link.attr('id')), this.onAjaxLoad);
	    	  this.showLoading();
	    	}
    	  	else {
    	  	  //if (this._link.hasClass('artibox_login')) this.options.isLogin = true;
    	  	  this._container.load(this._link.attr('href'), this.onAjaxLoad);
	    	  this.showLoading();
	    	}
    	  }    	  
    	break;
      	case 'message':
    	  this._content = $('#artibox_'+id);
    	  this._container.html(this._content.html());
    	break;
      	case 'confirm':
    	  if ($('#artibox_'+id).html() != null) {
    	    this._content = $('#artibox_'+id);
    	    this._container.html(this._content.html());
    	  }
    	  else {
    	   	this._content = this._container;
    	   	this._container.html('<p>'+artilinki.options.lightbox.confirmation_default_message+'</p>');
    	  }
    	break;
	  }
  };

  /**
   * setOptions
   * sets up width, height, title and buttons, switching context 
   * @author fl0r3nt
   */
  Artibox.prototype.setOptions = function() {
	this._container.dialog('option', 'width', this.options.width);
	this._container.dialog('option', 'height', this.options.height);
	if (this.options.minwidth != null) this._container.dialog('option', 'minWidth', this.options.minwidth);
	if (this.options.minheight != null) this._container.dialog('option', 'minHeight', this.options.minheight);
	if (this.options.maxwidth != null) this._container.dialog('option', 'maxWidth', this.options.maxwidth);
	if (this.options.maxheight != null) this._container.dialog('option', 'maxHeight', this.options.maxheight);
	this._container.dialog('option', 'title', this.getTitle());
	
	var buttons = {};
	switch (this._type) {
	  case "iframe":
		  this._container.dialog('option', 'buttons', {});
		  this._container.dialog('option', 'resizable', false);
		  var classDialog = 'ui-resizable ui-noresize nopadding';
		  if (this.options.dialogClass != '') classDialog+=' '+this.options.dialogClass;		  
		  this._container.dialog( "option", "dialogClass", classDialog);
		  var cadre = '<div class="ui-resizable-handle ui-resizable-n" unselectable="on" style="-moz-user-select: none;"></div>';
		  cadre +='<div class="ui-resizable-handle ui-resizable-e" unselectable="on" style="-moz-user-select: none;"></div>';
		  cadre +='<div class="ui-resizable-handle ui-resizable-s" unselectable="on" style="-moz-user-select: none;"></div>';
		  cadre +='<div class="ui-resizable-handle ui-resizable-w" unselectable="on" style="-moz-user-select: none;"></div>';
		  cadre +='<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se" style="z-index: 1001; -moz-user-select: none;" unselectable="on"></div>';
		  cadre +='<div class="ui-resizable-handle ui-resizable-sw" style="z-index: 1002; -moz-user-select: none;" unselectable="on"></div>';
		  cadre +='<div class="ui-resizable-handle ui-resizable-ne" style="z-index: 1003; -moz-user-select: none;" unselectable="on"></div>';
		  cadre +='<div class="ui-resizable-handle ui-resizable-nw" style="z-index: 1004; -moz-user-select: none;" unselectable="on"></div>';
		  cadre +='';
    	  $(cadre).insertAfter('#artibox');
    	  this._container.removeClass('morePaddingPlease');
	  break;
	  case "div":
		this._container.dialog('option', 'buttons', {});
	  break;
	  case "ajax":
		if (this.isSecure) {
			this._container.dialog('option', 'minHeight', 300);
			this._container.dialog('option', 'title', artilinki.options.lightbox.verification_code);
			this.setupConfirmButtons();
		}
		else if (this.options.isLogin) {
			this._container.dialog('option', 'buttons', {});
			this._container.dialog('option', 'title', artilinki.options.lightbox.auth_required);
		}
		else {
			this._container.dialog('option', 'buttons', {});
		}
	  break;
	  case "confirm":
		buttons[artilinki.options.confirm] = function() {artibox.submitDialog();};  
		buttons[artilinki.options.cancel] = this.close;
		this._container.dialog('option', 'buttons', buttons);
		this._container.dialog('option', 'buttons', buttons);
		this.setupConfirmButtons();
	  break;
	  case "message":
		buttons[artilinki.options.confirm] = this.close;
		this._container.dialog('option', 'buttons', buttons);
		if (this.options.isLogin) {
			this._container.dialog('option', 'title', artilinki.options.lightbox.auth_required);
		}
		$('.ui-dialog-buttonpane').find('button:last-child').addClass('bigBlueBtn');
	  break;	
	}
	if (this.options.dialogClass != '' && this._type != 'iframe') 
	  this._container.dialog( "option", "dialogClass", this.options.dialogClass );
	if (this._type != 'iframe' && this.options.hasNoPadding == false) {
	  this._container.addClass('morePaddingPlease').removeClass('nopadding');
	}
	else {
	  this._container.addClass('nopadding').removeClass('morePaddingPlease');
	}
  };
  
  /**
   * getOptionsFromClassNames
   * sets up the title by scanning element attributes
   * @author fl0r3nt
   */
  Artibox.prototype.getOptionsFromClassNames = function() {
	//Restore default options
	this.options.isWhiteClass = false;
	this.options.width = ''; this.options.height = 'auto';
	this.options.minheight = this.options.maxheight = this.options.minwidth = this.options.maxwidth = null;
	this.options.ajaxCallback = null;
	this.options.hasNoPadding = false;
	//Getting new options from link's css class names
	var classes = this._link.attr('class').split(' ');
	for(i=0; i < classes.length ; i++) {
	  if (classes[i].match(/artiwidth_/)) {
	    this.options.width = parseInt(this.getValueFromClassname(classes[i]));
      }
	  else if (classes[i].match(/artiheight_/)) {
	    this.options.height = parseInt(this.getValueFromClassname(classes[i]));
      }
	  else if (classes[i].match(/artiminwidth_/)) {
		this.options.minwidth = parseInt(this.getValueFromClassname(classes[i]));
	  }
	  else if (classes[i].match(/artiminheight_/)) {
		this.options.minheight = parseInt(this.getValueFromClassname(classes[i]));
	  }
	  else if (classes[i].match(/artimaxwidth_/)) {
		this.options.maxwidth = parseInt(this.getValueFromClassname(classes[i]));
	  }
	  else if (classes[i].match(/artimaxheight_/)) {
		this.options.maxheight = parseInt(this.getValueFromClassname(classes[i]));
	  }
	  else if (classes[i].match(/artititle_/)) {
		this.options.dialogClass = (this.options.dialogClass != 'test' ? this.options.dialogClass + ' ' : '') + this.getValueFromClassname(classes[i]);
	  }
	  else if (classes[i].match(/articlass_/)) {
		this.options.dialogClass = (this.options.dialogClass != 'test' ? this.options.dialogClass + ' ' : '') + this.getValueFromClassname(classes[i]);
		if (classes[i].match(/ui-red/)) {this.options.isWhiteClass = true;}
	  }
	  else if (classes[i].match(/secure/)) {
		this.options.isSecure = true;
	  }
	  else if (classes[i].match(/ajax_login/)) {
		this.options.isLogin = true;
	  }
	  else if (classes[i].match(/no-cache/)) {
		this.options.hasNoCache = true;
	  }
	  else if (classes[i].match(/no-padding/)) {
		this.options.hasNoPadding = true;
	  }
	  else if (classes[i].match(/articallback_/)) {
		this.options.ajaxCallback = this.getValueFromClassname(classes[i]);
	  }
	}
  };
  
  /**
   * setupConfirmButtons
   * add right classes to the dialog panel buttons
   * @author fl0r3nt
   */
  Artibox.prototype.setupConfirmButtons = function() {
	artibox._container.dialog('option', 'open', function() {
	  $('div.ui-dialog-buttonpane').find('button:nth-child(1)').addClass('bigBlueBtn marginRight5px');
	  $('div.ui-dialog-buttonpane').find('button:last-child').addClass('bigGreyBtn');
    });	
  };
  
  /**
   * onAjaxLoad
   * called when an ajax request is successfully done
   * Manage 404,401 and 500 error types 
   * @author fl0r3nt
   */
  Artibox.prototype.onAjaxLoad = function(response, status, xhr) {
    if (status == "error") {
      var msg = '';
      switch (xhr.status) {
        case 404:
          msg = artilinki.options.error_404;
        break;
        case 401:
          artibox._container.load(artilinki.options.lightbox.login_url, artibox.onAjaxLoad);
        break;
        case 500:
          msg = artilinki.options.error_500;
        break;
        default:
            msg = artilinki.options.error_500;
        break;
      }
      if (msg != '') {
    	artibox.options.hasNoCache = true;
    	artibox._link.addClass('no-cache');
        artibox._container.html(msg + xhr.status + " " + xhr.statusText);
        artibox.hideLoading();
      }
    }
    else {
      if (!artibox.options.hasNoCache) {
        artibox._loadedContent[artibox._link.name] = artibox._container.html();
      }
      //Launch callback function if necessary
      if(artibox.options.ajaxCallback != null) { 
    	  eval(artibox.options.ajaxCallback+'();');
      }
      artibox.initAjaxForm();      
      artibox.hideLoading();
      artibox.setupLoadingElements();
    }
  };
  
  /**
   * initAjaxForm
   * add an onSubmit listener to the form width the id "artibox_ajax_form"
   * this form will be submitted with an ajax request
   * @author fl0r3nt
   */
  Artibox.prototype.initAjaxForm = function() {
	var form = $('#artibox_ajax_form');
	if (form.length > 0) {
	  form.bind('submit', function(event) {
	    event.preventDefault();
	    artibox.submitAjaxForm();
	  });
	}  
  };
  
  /**
   * submitAjaxForm
   * submit a form call with ajax
   * @author fl0r3nt
   */
  Artibox.prototype.submitAjaxForm = function() {
	artibox.showLoading();
	var form = $('#artibox_ajax_form');
	$.ajax({
      type:'POST',
	  url: form.attr('action'),
	  data: form.serialize(),
	  success: artibox.onajaxFormSubmit,
	  error: artibox.onajaxFormError
	});	
     
  };
  
  /**
   * onajaxFormSubmit
   * called when a form was submitted with ajax
   * manage form result, if there's errors, display errors list, 
   * or execute the action define in 'data' retrun string
   * @author fl0r3nt
   */
  Artibox.prototype.onajaxFormSubmit = function(data)  {
    var posSpace = data.indexOf(' ', 0) != -1 ? data.indexOf(' ', 0) : data.length;
	var result = data.substr(0, posSpace);
	var succesReturn = false;
	switch(result) {
	  case "[success]":
		window.parent.document.location.href = artibox._link.attr('href');
		succesReturn = true;
	  break;
	  case "[success_login]":
		artibox._container.dialog('option', 'title', artilinki.options.lightbox.login_title);
		artibox.options.hasNoCache = true;
		artibox._link.addClass('no-cache').removeClass('secure').addClass('ajax_login');
		artibox._container.load(artilinki.options.lightbox.login_url, artibox.onAjaxLoad);
        artibox._loadedContent[artibox._link.name] = null;
        succesReturn = true;
	  break;
	  case "[success_reload]":
		window.parent.document.location.reload(true);
		succesReturn = true;
	  break;
	  case "[success_close]":
		artibox.close();
		succesReturn = true;
	  break;
	  case "[success_redirect]":
		var sep1 = data.indexOf('[[', posSpace);
		var sep2 = data.indexOf(']]', posSpace);
		if (sep1 == -1 || sep2==-1) {
		  alert(artilinki.options.error_redirect);
		  window.parent.document.location.href = artilinki.options.lightbox.homepage_url;
		}
		else {
		  window.parent.document.location.href = data.slice(sep1+2, sep2);
		}
		succesReturn = true;
	  break;
	  case "[success_callback]":
		var sep1 = data.indexOf('[[', posSpace);
		var sep2 = data.indexOf(']]', posSpace);
		if (sep1 == -1 || sep2==-1) {
		  alert(artilinki.options.error_redirect);
		  window.parent.document.location.href = artilinki.options.lightbox.homepage_url;
		}
		else {
		  var tmp = data.slice(sep1+2, sep2);
		  tmp = tmp.split(';');
		  var params = [];
		  for(var i=1; i < tmp.length; i++) {
			params[i]=tmp[i];
		  }
		  eval(tmp[0]+'(params);');
		}
		succesReturn = true;
	  break;
	}
	var errorDiv = $('#artibox_ajax_error');
	if (succesReturn == true) {
	  if (errorDiv.length > 0) {
		errorDiv.slideUp('slow');  
	  }
	  return true;
	}
	if (errorDiv.length > 0) {
	  errorDiv.html(data);
	}
	else {
	  var errorTag = '<div class="ajax_error" id="artibox_ajax_error">'+data+'</div>';
	  artibox._container.before(errorTag);
  	}
	if (artibox.options.isWhiteClass) {
		$('#artibox_ajax_error').addClass('whiteBg');	
	}
	artibox.hideLoading();
  };
  
  /**
   * onajaxFormError
   * manage 401, 404 and 500 errors on ajax form requests
   * @author fl0r3nt
   */
  Artibox.prototype.onajaxFormError = function(xhr, textStatus)  {
	if (textStatus == "error") {
	  var msg = '';
	  switch (xhr.status) {
	    case 404:
	      msg = artilinki.options.lightbox.error_404;
	    break;
	    case 401:
	      artibox._link.addClass('no-cache');
	      artibox.options.hasNoCache = true;
          artibox._container.load(artilinki.options.lightbox.login_url, artibox.onAjaxLoad);
        break;
	    default:
	      msg = artilinki.options.lightbox.error_500;
	    break;
	  }
	  if (msg != '') {
		artibox._link.addClass('no-cache');
        artibox.options.hasNoCache = true;
		artibox._container.html(msg + xhr.status + " " + xhr.statusText);
        artibox.hideLoading();
      }
	}
  };

  /**
   * getValueFromClassname
   * retrun value from the classname param. split on '_' and return last part
   * @author fl0r3nt
   */
  Artibox.prototype.getValueFromClassname = function(classname) {classname = classname.split('_'); return classname[1];};
  
  /**
   * getTitle
   * sets up the title by scanning element attributes
   * @author fl0r3nt
   */
  Artibox.prototype.getTitle = function() {
	  var title = this._link.attr('title');
	  title = title.replace(/<script>/gi, "");
	  title = title.replace(/<\/script>/gi, "");
	  return  title; 
  };

  /**
   * setName
   * define the name of the content 
   * @author fl0r3nt
   */
  Artibox.prototype.setName = function()  {
    if (this._link.attr('name') != '') {
      this._link.name = this._link.attr('name');
    }
    else {
      if (this._link.name == null) {
        this._link.name = 'content_'+this._offset;
        this._offset++;
      }
    }
  };

  /** 
   * get object id from eltId
   * @author fl0r3nt
   */
  Artibox.prototype.getSequenceIdFromElementId = function(eltId) {eltId = eltId.split('_'); eltId = eltId[1]; return eltId;};
  
  /** 
   * close the dialog box
   * @author fl0r3nt
   */
  Artibox.prototype.close = function() { artibox._container.dialog('close');};
  
  /**
   * call the dialog targeted link
   * @author fl0r3nt
   */
  Artibox.prototype.submitDialog = function() {artibox.showLoading(); window.location.href = artibox._link.attr('href'); return false;};
  
  
  /**
   * showOverlay
   * animate overlay's apparition
   * @author fl0r3nt
   */
  Artibox.prototype.showOverlay = function(event, ui)  {
    $('div.ui-widget-overlay').css('opacity', 0);
    $('div.ui-widget-overlay').fadeTo('slow', 0.5);
    $(event.currentTarget).unbind('dialogopen', artibox.showOverlay);
  };
  
  /**
   * showLoading
   * display loading : there is a different loading for each type of artiboxes
   * @author fl0r3nt
   */
  Artibox.prototype.showLoading = function(loadingType) {
	var type = loadingType != undefined ? loadingType : this._type;
	var loadingDiv = ''; var targetDiv = null;
	var fadeEffect = false; var isWhite = false;
	switch(type) {
	  case "ajax":
	  default:
		loadingDiv = '<div id="ajax_loading"><div class="ajax_loading_bg"></div><div class="ajax_loading_spinner"></div></div>';
		loadingDivId = 'ajax_loading';
		targetDiv = artibox._container;
		fadeEffect = true;
		isWhite = artibox.options.isWhiteClass;
	  break;
	  case "iframe":
		loadingDiv = '<div id="iframe_loading"></div>';
		loadingDivId = 'iframe_loading';
		targetDiv = artibox._container;
		isWhite = artibox.options.isWhiteClass;
	  break;
	  case "iframe_inside":
		loadingDiv = '<div id="iframe_inside_loading"><div class="iframe_inside_loading_bg"></div><div class="iframe_inside_loading_spinner"></div></div>';
		loadingDivId = 'iframe_inside_loading';
		targetDiv = $('body');
		isWhite = $('body').hasClass('white_box') ? true : false;
	  break;
	}
	
	var loadingElt = $('#'+loadingDivId); 
	if (loadingElt.length == 0) {
	  targetDiv.before(loadingDiv);
	  loadingElt = $('#'+loadingDivId);
	  loadingElt.css('z-index','99');
	  $('div.ui-dialog-titlebar').css('z-index','300');
	}
	if (isWhite) loadingElt.addClass('white');
	else loadingElt.removeClass('white');
	if (fadeEffect == true) loadingElt.fadeIn();
	else loadingElt.css('display', 'block');
  };
  
  /**
   * hideLoading
   * remove loading from background
   * @author fl0r3nt
   */
  Artibox.prototype.hideLoading = function(loadingType) { 
	switch(this._type) {
	  case "ajax":
	  default:  
		$('#ajax_loading').fadeOut();
	  break;
	  case "iframe":
		$('#iframe_loading').remove();
	  break;
	}
  };
  
  /**
   * hideParentIframeLoading
   * hide loading div, called from iframe
   * @author fl0r3nt
   */
  Artibox.prototype.hideParentIframeLoading = function() { 
	  window.parent.artibox.hideLoading();
  }; 
  
   /**
   * setupLoadingElements
   * add onclick listener for all elements with displayLoadingElt css class
   * to display loading
   * @author fl0r3nt
   */
  Artibox.prototype.setupLoadingElements = function(iframe) {
	var targetElement = iframe == 1 ? $('body') : artibox._container;
	targetElement.find(".displayLoadingElt").each(function(i, elt){
	  $(elt).click(function(e) {
	    if (artibox._type == 'iframe') {
		  artibox.showLoading('iframe_inside');
		}
		else {
		  artibox.showLoading();
		}
	  });
	});
  };
  
  /**
   * emptyContainer
   * remove all content from main container, stop iframe's loading when box is closed before end of loading
   * @author fl0r3nt
   */
  Artibox.prototype.emptyContainer = function(event) {
	artibox.options.dialogClass = '';
	artibox._container.html('&nbsp');
    artibox._container.unbind('dialogclose', artibox.emptyContainer);
  };
  
  Artibox.prototype.getIframeUrl = function() {
    var l = this._link.attr('href').toString();
    if (l.indexOf("?")!=-1) {l+= '&iframe=1';}
    else {l+= '?iframe=1';}
    l+= this.options.isWhiteClass == true ? '&whitebox=1':'';
    return l;
  };
  
  /**
   * redirect
   * redirect current page to url
   * @author fl0r3nt
   */
  Artibox.prototype.redirect = function(url) {
	artibox.showLoading();
	window.parent.document.location.href = url;
  };
}