/**
* This class implements flash API functions required by main application
*/

function FlashProxy() {
  
/*** Introduction video reference  */
  this.movie = null;
  
/*** Globally defined supported language list  */
  this.langList = "";

/*** Globally defined supported section list - Home Section is exclude  */
  this.section = ["shows","multimedias","other-activities","about"];
  
/*** isReady() : boolean   *** Return true if movie is ready, false otherwise  */
  this.isReady = function() {
    return this.movie == null;
  };
  
/*** hasToShowVideo() : boolean  *** Return true if flash application has to show introduction video, false otherwise  */
  this.hasToShowVideo = function() {
    if(this.getCookie("flashintro") != "1") {
      this.setCookie("flashintro", "1");
      return true;
    }else{
      return false;
    }
    return true;
  };
  
/*** hasToPlayAmbientMusic() : boolean *** Return true if flash application has to play ambient music, false otherwise */
  this.hasToPlayAmbientMusic = function() {
    if(this.getCookie("ambientmusic") == "0") {
      return false;
    }else{
      return true;
    }
  };
  
/*** toggleAmbientMusic() : void  */
  this.toggleAmbientMusic = function(mustplay) {
    if(mustplay == "true") {
      this.setSessionCookie("ambientmusic", "1");
    } else {
      this.setSessionCookie("ambientmusic", "0");
    }
  };
  
/*** openShadowBox(href, rel, title) : void  *** Open a Shadowbox dialog  */
  this.openShadowBox = function(href, rel, title) {
    if(rel.toLowerCase().indexOf("shadowbox") != -1 && Shadowbox != undefined) 
    {
      Shadowbox.open(this.parseShadowboxParameters(href, rel, title));
    }
  };

/*** openShadowBoxImageGallery(obj[]) : void
  * Open a Shadowbox Image Gallery dialog  */
  this.openShadowBoxImageGallery = function(images) {
    if(Shadowbox != undefined) 
    {
      // Créer les anchor dans le DOM à partir des paramètres d'images
      // Faire un Shadowbox.setup() avec ces anchors
      // Ouvrir la gallery (en ajoutant un callback au close pour libérer les resources du DOM

      //Shadowbox.open(this.parseShadowboxParameters(href, rel, title));
    }
  };

/*** getFullURL(swf) : string
  * returns the full URL of the window  */
  this.getFullURL = function() {   
     return window.location.href;
  };

/*** shareURL(offsetLeft, offsetTop, title) : string
  * opens the "add this" API  */
  this.shareURL = function(offsetLeft, offsetTop, title) {
    var div = document.getElementById('add_this_div');
    if(!div) {
      div = document.createElement('div');
      div.id = 'add_this_div';
      document.body.appendChild(div);
    }

    var a = document.getElementById('add_this_anchor');
    if(!a) {
      a = document.createElement('a');
      a.id = 'add_this_anchor';
      div.appendChild(a);
    }

    if(!div.style) {
      div.position = 'fixed';
      div.left = this.getAddThisOffsetLeft(offsetLeft);
      div.top = this.getAddThisOffsetTop(offsetTop);
    } else {
      $(div).css('position', 'absolute');
      $(div).css('left', this.getAddThisOffsetLeft(offsetLeft));
      $(div).css('top', this.getAddThisOffsetTop(offsetTop));
    }

    var config = addthis_config;
    var url = document.location.href;
    title = title != '' ? title : 'Cirque du Soleil';
    config.ui_offset_left = 0;
    config.ui_offset_top = 0;
    config.ui_hover_direction = 1;
    addthis_open(a, '', null, null, config, {url: url, title: title});
  };

/*** getAddThisOffsetLeft(offsetTop) : int
  * gets the offsetLeft value to show the addthis dropup  */
  this.getAddThisOffsetLeft = function(offsetLeft) {
    var fullscreen = ($(document).width() - parseInt(offsetLeft) < 125) ? true : false;

    if($.browser.msie && $.browser.version == '6.0') {
      offsetLeft += fullscreen ? -45 : -246;
    } else {
      offsetLeft += fullscreen ? -45 : -235;
    }

    return offsetLeft;
  };
  
/*** getAddThisOffsetTop(offsetTop) : int
  * gets the offsetTop value to show the addthis dropup  */
  this.getAddThisOffsetTop = function(offsetTop) {
    if($.browser.msie && $.browser.version == '6.0') {
      offsetTop += 5;
    } else if($.browser.mozilla) {
      offsetTop += 20;
    } else {
      offsetTop += 5;
    }

    return offsetTop;
  };

/*** initialize(swf) : void
  * Initialize proxy application  */
  this.initialize = function(swf) {        
    if (navigator.appName.indexOf("Microsoft") != -1) {
      this.movie = window[swf];
    } else {
      this.movie =  document[swf];
    }
    
    if (this.movie != null) {
      this.movie.ready();
    }
  };
  
/*** getCookie(name) : string
  * Return a cookie value if exists, null otherwise  */
  this.getCookie = function(name) {
    var cname = name + "=";                
    var dc = document.cookie;

    if (dc.length > 0) {
      begin = dc.indexOf(cname);        
      if (begin != -1) {
        begin += cname.length;        
        end = dc.indexOf(";", begin); 
        if (end == -1) {
          end = dc.length; 
        }
        return unescape(dc.substring(begin, end)); 
      }  
    } 
    return null;
  };
  
/*** setCookie(name, value) : void
  * Sets a cookie value  */
  this.setCookie = function(name, value) {
    var expiration = new Date(); 
    expiration.setTime(expiration.getTime() + (100000*1000000));  // 4 years  
    document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expiration.toGMTString() + ";";
  };
  
/*** setSessionCookie(name, value) : void
  * Sets a cookie value during only the current browser session  */
  this.setSessionCookie = function(name, value) {
    document.cookie = name + "=" + escape(value) + "; path=/;";
  };

/*** exists() : string
  * Returns true if the section  is found in the array  */
  this.exists = function(o,s) {
	for(var i = 0; i < o.length; i++)
      if(o[i] === s)
         return true;
	return false;
}

/*** getCirqueClubMemberStatus() : string
  **/
  this.getCirqueClubMemberStatus = function() {
    //Cirque Member processing 
	if(getCookie("cds_clubmember_id") != ""){
		return "cirque club member";
	}else{
		if(getCookie('eVar2Cookie')=="cirque club member"){
			return "cirque club member";
		}else{
			return "non-club member";
		}
	}
}


/*** getSectionName() : string
  * Returns the name of the section if it found  */
  this.getSectionName = function(lang) {
    try {

		var strInfo = document.location.hash.substr(1);
		if(strInfo == ("/" + lang + "/home.aspx")){
			return "home";		
		}
		strInfo = strInfo.split('.')[0].replace('/' + lang + '/home', '');
		if(strInfo.indexOf("/") == 0) strInfo = strInfo.substring(1, strInfo.length);//drop the first slash	
		if(strInfo.lastIndexOf("/") > 0)strInfo = strInfo.substring(0, strInfo.indexOf("/"));	

		return strInfo;
    }catch(ex){
		//alert("getSectionName : "+ex);
		return "";
    }	
  }

/*** extractInfo(string, startValue, endValue) : void
  * Extract string between StartString and EndString  */
  this.extractInfo = function(str, startTag, endTag) {
    try {
      var result = "";
      if(str.indexOf(startTag)!= -1 ) {
        str = str.substring(str.indexOf(startTag) + startTag.length); //remove before the first TAG
        result = str.substring(str.lastIndexOf(startTag), str.indexOf(endTag));
        result = result.substring(result.indexOf('"')+1, result.length); //GET hier DATA between '
      }
      return result.replace(/^\s+|\s+$/g,"").replace('\n', '', 'g');//Trim Space and Carriage Return
    } catch(ex) {
      //alert("extractInfo : "+ex);
    }	
  };

/*** updateStatistics(content) : void
  * Generate a call to update page statistics  */
  this.updateStatistics = function(content) {
    var currentLang = this.getCurrentLang();
	var currentLocation = this.getSelectedLocation();
	content = "s.pageURL = 'http://" + document.location.host + "/" + currentLang + "/home" + currentLocation + ".aspx';" + content;  

	try {
	  var url = window.location.href;
	  if( (url.indexOf(".aspx")!= -1 )&&(url.indexOf("#")!= -1) ) {
		if(content.indexOf("Google Analytics")==-1){
//			content = "var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-15123064-2'],['_trackPageview'],['_trackPageLoadTime']);";
//		} 
//		else{
			if( content.indexOf("tools:ticket-finder")!= -1 ){
				content = content.replace('s.channel = "tools"', 's.channel = "ticket-finder"');
				content = content.replace('s.channel = ""', 's.channel = "ticket-finder"');
				//alert("TICKET FINDER");
			}
			if( content.indexOf("tools:ticket-finder")== -1 ){
				content = content + "var s_code=s.t();if(s_code)document.write(s_code);";
				//alert(content);
			}
		 }

	     eval(content);

if(content.indexOf(" Shadowbox Page Override")!=-1){
var options = {autoDimensions: true, displayNav: true, displayCounter: false};
      Shadowbox.open({height: strHeight, width: strWidth, content: strShadoxBox, player:'iframe'}, options );
}
	  }else{
	      //alert("ByPass STAT");
	  }
	} catch(ex) {
	  alert("updateStatistics : "+ex);
	}
  };
  
/*** updateTitle() : Page title  * Extract TITLE from page  */
  this.updateTitle = function() {
	var result = "";
 	var url = 'http://' + document.location.host + document.location.hash.substr(1);

	try {
	  $.ajax({
		url: url,
		async: false,
		dataType: "html",
		success: function(data){ 
			var info = proxy.extractInfo(data, "<title>", "</title>");
			if(info.length > 0){
			  result = info;
			}else{
			  result = document.title;
			};			
		}
      });	
	  return result;
	}catch(ex){
	  //alert("updateTitle : "+ex);
	}
	return result;
  };

/*** getSelectedLocation() : string
  * Returns the selected location (region/country)   */
  this.getSelectedLocation = function() {
  var url = window.location.href;
  
    try {
      var currentLang = this.getCurrentLang();
      var langList = getCountryLangList();
      var mnemonic = getCountryMnemonic();
	  
	  // Update TITLE		
	  document.title = this.updateTitle();
	  
	  var sectionName = this.getSectionName(currentLang); //alert("SECTION: " + sectionName); 
	  
	  if( ((langList.indexOf(currentLang) < 0)||(url.indexOf(mnemonic) < 0))&& ((sectionName != "")&&(this.exists(this.section, sectionName) == false)) ) {
		 mnemonic = "";
	  }
	  if( mnemonic.length == 0){
		// try to validate the current URL (and receive the cookie)
		mnemonic = this.validateUrl();
		langList = getCountryLangList();
	  }
	  if((mnemonic.length > 0) && (mnemonic.indexOf("/") != 0) ) {
		 mnemonic = "/" + mnemonic;
	  }
	  if(langList.indexOf(currentLang) < 0) {
		 mnemonic = "";
	  }		  

      return mnemonic;
    } catch(ex) {
		//alert("getSelectedLocation : "+ex);
    }
    return "";
    
  };
  
/*** validateUrl() : void  * Verify if the URL is présent in Welcome page  */  
  this.validateUrl = function() {
    var currentLang = proxy.getCurrentLang();
  
    // 1- Extract mnemonic from current URL
    var hash = document.location.hash.substr(1);
	if(hash == ('/' + currentLang + '/home.aspx')){
		hash = ('/' + currentLang + '/home') + getCountryMnemonic(); //HACK for the home without country
	}
    var url = 'http://' + document.location.host + '/en/welcome.aspx?search=true';
    var mnemonic = hash.split('.')[0].replace('/' + currentLang + '/home', '');
   if(mnemonic.indexOf("/home/") > 0) mnemonic = mnemonic.substring(mnemonic.lastIndexOf("/home/")+5, mnemonic.length);
	
    // 2- Get requested page HTML
    $.ajax({
      type: "GET",
      url: url,
      dataType: "html",
      success: this.postValidate,
      error: this.onInvalidMnemonic,
      async: false
    });
    return mnemonic;
  };

/*** postValidate() : void  * Change the cookie if the URL is présent in Welcome page  and return mnemonic */    
  this.postValidate = function(xml) {
    var langs = '';
	var code = '';
    var currentLang = proxy.getCurrentLang();

    // 1- Extract mnemonic from current URL
    var hash = document.location.hash.substr(1);
	var cookieMnemonic = getCountryMnemonic();
	if((hash == ('/' + currentLang + '/home.aspx'))&&(cookieMnemonic.length > 0)){
		hash = '/' + currentLang + '/home' + cookieMnemonic + '.aspx'; //HACK for the home without country
	}
	var mnemonic = hash.split('.')[0].replace('/' + currentLang + '/home', '');
	//****** BUG in IE7 with jQuery ********
	regex = new RegExp(/<([^\s]+).*?id="([^"]*?)".*?onclick="([^"]*?)"*?>(.+?)<\/\1>/gi);
	matches = xml.match(regex);
	mnemonicTag = currentLang + mnemonic.replace(/\//g, '-');
	
//	alert(mnemonic);
	
	for (i in matches) {
	  try {
		parts = matches[i].replace('\n', '', 'g');

		//Grep language-country "id"  of the href link
		mneonicInfo = parts.substring(parts.indexOf('id="') + 4, parts.length);
		mneonicInfo = mneonicInfo.substring(0, mneonicInfo.indexOf('"') );	

		//Grep javascript "onClick" event
		eventClick = parts.substring(parts.indexOf('onclick="') + 9, parts.length);
		eventClick = eventClick.substring(0, eventClick.indexOf(')') + 1);

		if((mneonicInfo)&&(eventClick)&&(mneonicInfo == mnemonicTag)&&(eventClick.indexOf("setCookies(")!= -1 )){
		code = eventClick;
		break;
		}
	  }catch(ex){
		//alert("postValidate PARTS : "+ex);
	  }		  
	}

     // 2- Create cookies (by clearing old cookies)
    if(code && code != '') {
//alert("AFTER CLEAR COOKIE... EXECUTE code:"+code);	
      clearCookies();
      eval(code);
    } else {
	  mnemonic = "";
	  return "";
      //proxy.onInvalidMnemonic();
    }
   return mnemonic;
  };
  
  this.onInvalidMnemonic = function() {
    var currentLang = proxy.getCurrentLang();
	//alert("invalid mnemonic redirect");
    document.location.href = '/' + currentLang + '/welcome.aspx?change-country-language=true';
  };
 
/*** getCurrentLang() : string  * Return the current language code (correcting the Akamai cookie problem)  */
  this.getCurrentLang = function() {
	var lang = "";
	var url = document.location.href;
    var currentLang = getCookie('website#lang');
    //check if current language is part of the url
    if(document.location.href.indexOf("/" + currentLang + "/") < 0) {
      var lang = document.location.href;
      lang = lang.replace("http://" + document.location.host + "/", "");
      var last = lang.indexOf("/");
      if(last > 0) {
        lang = lang.substring(0,last);
        currentLang = lang;
      }
    }
/*
   else
   {
      var hash = info.split('#'); 
      if (hash[1] == null ){ 
        lang = hash[0]; 
      } else{
        lang = hash[1]; 
      } 
      lang = lang.substring(1, lang.length);
      if(lang.indexOf("/") > 0){
        lang = lang.substring(0,lang.indexOf("/"));
      }else{
        lang = "";
      }
      currentLang = lang;
   }
*/
    return currentLang;
  };
  
/*** parseShadowboxParameters(href, rel, title) : array  * Return an associative array of the shadowbox parameters  */
  this.parseShadowboxParameters = function(href, rel, title) {
    var params = {};
    if (href != '') { 
      params.content = href;
    }
    if (title != '') { 
      params.title = title;
    }
    var array = rel.split(";");
    for (i = 0; i < array.length; i++) {
      var value = array[i];
      value = value.toLowerCase();
      
      // Gets gallery name
      if(value.indexOf("shadowbox") != -1 && value.indexOf("[") != -1) {
        index = value.indexOf("[") + 1;
        end = value.indexOf("]");
        params.gallery = value.substring(index, end);
      }
      // Gets width
      if(value.indexOf("width") != -1 && value.indexOf("=") != -1) {
        index = value.indexOf("=") + 1;
        params.width = value.substring(index);
      }
      // Gets height
      if(value.indexOf("height") != -1 && value.indexOf("=") != -1) {
        index = value.indexOf("=") + 1;
        params.height = value.substring(index);
      }
    }
    params.player = 'iframe';

    return params;
  };
}

proxy = new FlashProxy();
