YAHOO.namespace("Unyk.Common");
var Unyk = YAHOO.Unyk;


//*****************************************************************************
//
//	General Functions
//
//*****************************************************************************

//
//	Shorthands.
//
var $ = YAHOO.util.Dom.get,
	Connect = YAHOO.util.Connect,
	Dom = YAHOO.util.Dom,
	Event = YAHOO.util.Event,
	JSON = YAHOO.lang.JSON;


//
//
//
function ShowThis(item)
{
	if (document.getElementById(item)) {
		document.getElementById(item).style.visibility = "visible";
		document.getElementById(item).style.display = "";
	}
}

//
//
//
function HideThis(item)
{
	if (document.getElementById(item)) {
		document.getElementById(item).style.visibility = "hidden";
		document.getElementById(item).style.display = "none";
	}
}


//
//
//
function ToggleThis(item)
{
	if (document.getElementById(item).style.visibility == "hidden")
	{
		ShowThis(item);
		return true;
	}
	else
	{
		HideThis(item);
		return false;
	}
}


//
//	Handles some rendering issues with browsers. Only IE 6 seems to have
//	problems at the moment but the function is "generic".
//
//	obj:		String representing the object. Default is document.body.
//	duration:	Time elapsed before the fix is applied (in milliseconds).
//				Default is 500.
//
Unyk.Common.RenderingFix = function(obj, duration)
{
	if (YAHOO.env.ua.ie == 6)
	{
		if (!obj) obj = "document.body";
		if (!duration) duration = 500;

		var cmd = "Unyk.Common.DoRenderingFixIE6(" + obj + ");";
		setTimeout(cmd, duration);

		//Event.on(window, "resize", Unyk.Common.DoRenderingFixIE6);
	}
}

//
//	Apply the rendering fix for IE 6.
//
Unyk.Common.DoRenderingFixIE6 = function(obj)
{
	if (obj)
	{
		Dom.setStyle(obj, "display", "inline");
		Dom.setStyle(obj, "display", "block");
	}
}


//*****************************************************************************
//
//	Popup System
//
//*****************************************************************************

//
//	...
//
function openWin(nomsite, nomtitre, width, height)
{
	var winleft = (screen.width - width) / 2;
	var winUp = (screen.height - height) / 2;	
	var win = window.open("",nomtitre,"toolbar=no,left="+winleft+",top="+winUp+",location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height);

	if (win!=null) {
		win.location=nomsite;
		win.focus();
	}
}


//
//	...
//
function openWinWithScroll(nomsite, nomtitre, width, height)
{
	var winleft = (screen.width - width) / 2;
	var winUp = (screen.height - height) / 2;	
	var win = window.open("",nomtitre,"toolbar=no,left="+winleft+",top="+winUp+",location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=" + width + ",height=" + height);

	if (win!=null) {
		win.location=nomsite;
		win.focus();
	}
}

//
//	...
//	Note: replaces the target="_blank" attribute from links.
//
Unyk.Common.AddTargetBlankHandler = function()
{
	YAHOO.util.Dom.getElementsByClassName("target-blank", "a", null, 
		function(e)
		{
			if (e && e.href)
			{
				YAHOO.util.Event.on(e, "click",
					function(e, args)
					{
						YAHOO.util.Event.preventDefault(e);
						window.open(args);
					},
					e.href
				);
			}
		}
	);
}



//*****************************************************************************
//
//	Swaping System
//
//*****************************************************************************

//
//  v3.0
//
function MM_swapImgRestore() { 
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

//
//  v3.0
//
function MM_preloadImages() { 
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

//
//  v4.01
//
function MM_findObj(n, d) { 
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

//
//  v3.0
//
function MM_swapImage() {
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}



//*****************************************************************************
//
//	String Functions
//
//*****************************************************************************


//
//	Ensures that the given txtBox object never goes 
//	over the maximum allow text length
//
//	Returns: Dictionary of current status
//
function EnsureMaxLength(txtBox, maxLength)
{
	var stat = {
		Length: 0, 
		Remaining: 0
	};

	if (txtBox)
	{
		stat.Length = txtBox.value.length;

		if (stat.Length > maxLength) 
		{
			txtBox.value = txtBox.value.substr(0, maxLength);
			stat.Length = maxLength;
		}
		
		stat.Remaining = maxLength - stat.Length;
	}	

	return stat;
}


//
//	Resizes vertically the given textArea object so contained 
//	text is displayed.
//
function ResizeTextArea(textArea, minRows, maxRows, rowsOffset)
{
	if (textArea && textArea.rows)
	{
		var sValues = textArea.value.split("\n");
		var nRows = 1;
		for (x = 0; x < sValues.length; x++) 
		{
			if (sValues[x].length >= textArea.cols)
				nRows += Math.ceil(sValues[x].length / textArea.cols);
		}
		nRows += sValues.length;

		if (rowsOffset)
			nRows -= rowsOffset;

		if (nRows >= maxRows)
			nRows = maxRows;
		if (nRows <= 1)
			nRows = minRows;

		textArea.rows = nRows;
	}
}


//
//	...
//
function trim(strText)
{
	while (strText.substring(0,1) == ' ') 
		strText = strText.substring(1, strText.length);    
	while (strText.substring(strText.length-1,strText.length) == ' ')
		strText = strText.substring(0, strText.length-1);
	return strText;
} 

//
//  Skip leading and trailing whitespace and return everything in between
//
String.prototype.trim = function() 
{
	var x = this;
		
	if(x != null) {
		x=x.replace(/^\s*(.*)/, "$1");
		x=x.replace(/(.*?)\s*$/, "$1");
	}
  
	return x;
}

//
//
//
function left(str, n)
{
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else
		return String(str).substring(0,n);
}

//
//
//
String.prototype.left = function(n) 
{
	var str = this;
	
	if (str != null) {
		if (n <= 0)
			str = "";
		else if (n > String(x).length)
			str = str;
		else
			str = String(str).substring(0,n);
	}
  
	return str;
}

//
//
//
function right(str, n)
{
	if (n <= 0)
	   return "";
	else if (n > String(str).length)
	   return str;
	else {
	   var iLen = String(str).length;
	   return String(str).substring(iLen, iLen - n);
	}
}

//
//
//
String.prototype.right = function(n) 
{
	var str = this;
	
	if (str != null) {
		if (n <= 0)
			str = "";
		else if (n > String(x).length)
			str = str;
		else {
			var iLen = String(str).length;
			str = String(str).substring(iLen, iLen - n);
		}
	}
	
	return str;
}

//
//
//
String.prototype.format = function() 
{		
	var s = this;

	for (var i = 0; i < arguments.length; i++)
	{
		s = s.replace(new RegExp("\\{"+ i +"\\}", "gi"), arguments[i]);
	}

	return s;
}


//
//
//
String.isNullOrEmpty = function(s)
{
	return (s == null || s === "");
}



//*****************************************************************************
//
//	Array Functions
//
//*****************************************************************************

/*
Source: http://svn.mootools.net/tags/1-10/Native/Array.js

Property: indexOf
	This method is provided only for browsers without native *indexOf* support.
	For more info see <http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf>

	*indexOf* compares a search element to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

Arguments:
	item - any type of object; element to locate in the array
	from - integer; optional; the index of the array at which to begin the search (defaults to 0)

Example:
	>['apple','lemon','banana'].indexOf('lemon'); //returns 1
	>['apple','lemon'].indexOf('banana'); //returns -1
*/

Array.prototype.indexOf = function(item, from)
{
	var len = this.length;
	var start = (from < 0) ? Math.max(0, len + from) : from || 0;
	
	for (var i = start; i < len; i++)
	{
		if (this[i] === item) return i;
	}
	
	return -1;
}



/*
Property: remove
	Removes all occurrences of an item from the array.

Arguments:
	item - the item to remove

Returns:
	the Array with all occurrences of the item removed.

Example:
	>["1","2","3","2"].remove("2") // ["1","3"];
*/

Array.prototype.remove = function(item)
	{
	var i = 0;
	var len = this.length;
	while (i < len){
		if (this[i] === item){
			this.splice(i, 1);
			len--;
		} else {
			i++;
		}
	}
	return this;
	}


/*
Property: removeAt
	Removes the item a the specified position.

Arguments:
	pos - the position of the item to be removed.

Returns:
	the Array with the item at the specified position removed.

Example:
	>["1","2","3","2"].removeAt(1) // ["1","3","2"];
*/

Array.prototype.removeAt = function(pos)
{
	this.splice(pos, 1);
	return this;
}


/*
Property: contains
	Tests an array for the presence of an item.

Arguments:
	item - the item to search for in the array.
	from - integer; optional; the index at which to begin the search, default is 0. If negative, it is taken as the offset from the end of the array.

Returns:
	true - the item was found
	false - it wasn't

Example:
	>["a","b","c"].contains("a"); // true
	>["a","b","c"].contains("d"); // false
*/

Array.prototype.contains = function (element) 
  {
   for (var i = 0; i < this.length; i++) 
   {   
		if (typeof(element) == "string")
		{
			if (this[i].toLowerCase() === element.toLowerCase())
			{
				return true;
			}
		}
		else
		{
			if (this[i] == element)
			{
				return true;
			}
        }
   }
   return false;
  }



/*
Property: merge
	merges an array in another array, without duplicates. (case- and type-sensitive)

Arguments:
	array - the array to merge from.

Example:
	>['Cat','Dog'].merge(['Dog','Coala']); //returns ['Cat','Dog','Coala']
*/

Array.prototype.merge = function(array)
	{
	for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
	return this;
	}

/*
Property: include
	includes the passed in element in the array, only if its not already present. (case- and type-sensitive)

Arguments:
	item - item to add to the array (if not present)

Example:
	>['Cat','Dog'].include('Dog'); //returns ['Cat','Dog']
	>['Cat','Dog'].include('Coala'); //returns ['Cat','Dog','Coala']
*/

Array.prototype.include = function(item)
	{
	if (!this.contains(item)) this.push(item);
	return this;
	}


/*
Property: clean
	Parameter: to_delete <- element to delete from the array
*/

Array.prototype.clean = function(to_delete)
{
   var a;
   for (a = 0; a < this.length; a++)
   {
      if (this[a] == to_delete)
      {
         this.splice(a, 1);
         a--;
      }
   }
   return this;
}



/*
Property: sort
*/
Array.prototype.sort = function()
	{
	for(i=0;i<this .length;i++)
		{
			for(j=i+1;j<this.length;j++)
			{
				if(Number(this[i]) >Number(this[j]))
				{
					temp = this[j];
					this[j] = this[i];
					this[i] = temp;
				}
			}
		}
	}


/*
Property: removeDuplicate
*/
Array.prototype.removeDuplicate = function()
	{
	// Here we remove duplicate values from first array
	var array4 = new Array;
	for(var i=0; i<this.length; i++) 
		{
			  var xx = true;
			for(var j=i+1; j<this.length; j++)
			{
				if(this[i] == this[j])
					xx = false;
			}	
			if(xx == true)
				array4.push(this[i]);
		}
	return array4;
	}


//*****************************************************************************
//
//	Date Functions
//
//*****************************************************************************

//
//
//
function isDate(d)
{
	if (d == "")
		return false;

	e = new RegExp("^[0-9]{1,2}\/[0-9]{1,2}\/([0-9]{2}|[0-9]{4})$");

	if (!e.test(d))
		return false;
		
	j = parseInt(d.split("/")[0], 10);
	m = parseInt(d.split("/")[1], 10);
	a = parseInt(d.split("/")[2], 10);
	
	if (a < 1000) {
		if (a < 89)
			a += 2000;
		else
			a += 1900;
	}
	
	if (a%4 == 0 && a%100 !=0 || a%400 == 0)
		fev = 29;
	else
		fev = 28;
	
	nbJours = new Array(31,fev,31,30,31,30,31,31,30,31,30,31);
	
	// retourne vrai si le jour est bien entre 1 et le bon nombre de jours, idem pour les mois, sinon retourn faux
	return ( m >= 1 && m <=12 && j >= 1 && j <= nbJours[m-1] );
}



//*****************************************************************************
//
//	Captcha Functions
//
//*****************************************************************************

//
//
//
function ReloadCaptchaImg(CaptchaImgName)
{
	if ($(CaptchaImgName))
	{
		var CaptchaDefaultStyle1	= 1		// Distorsion
		var CaptchaDefaultStyle2	= 30	// ThinWavyLetters
		var CaptchaDefaultStyle3	= 8		// Stitch
		var CaptchaDefaultStyle4	= 39	// Graffiti2
		var CaptchaDefaultStyle5	= 43	// InBandages
		
		var ran_number				= Math.floor(Math.random()*5); 
		var CaptchaImg				= $(CaptchaImgName).src;		
		var pos						= CaptchaImg.indexOf('&TextStyle=');		
		var NewCapchaImgSrc			= CaptchaImg.substring(0, pos);
			
		NewCapchaImgSrc = NewCapchaImgSrc + "&TextStyle=" + eval("CaptchaDefaultStyle"+(ran_number*1+1));
		
		$(CaptchaImgName).src = NewCapchaImgSrc + "&rnd=" + Math.random();
	}
}




//*****************************************************************************
//
//	Ads Functions
//
//*****************************************************************************

//
//	...
//
function RenderFoxAds()
{
	var baseUrl = "http://ad.directaclick.com/st?ad_type=iframe&ad_size={0}&section=284129";
	var sizes = ["120x600", "728x90", "468x60", "120x90", "160x600"];
	
	
	for (size in sizes)
	{
		if ($("fox"+ sizes[size]))
		{
			//$("fox"+ sizes[size]).src = baseUrl.format(sizes[size]);
			
			$("fox"+ sizes[size]).innerHTML = 
				"<iframe "+
					"id=\"fox\""+ sizes[size] +"\" "+
					"frameborder=\"0\" "+
					"marginwidth=\"0\" "+
					"marginheight=\"0\" "+
					"scrolling=\"no\" "+
					"width=\""+ sizes[size].split("x")[0] +"\" "+
					"height=\""+ sizes[size].split("x")[1] +"\" "+
					"src=\""+ baseUrl.format(sizes[size]) +"\">"+
				"</iframe>";
		}
	}
}



//*****************************************************************************
//
//	Omniture
//
//*****************************************************************************

//
//	...
//
Unyk.Common.Omniture = function()
{
};

Unyk.Common.Omniture.prototype = 
{
	//*************************************************************************
	//
	//	Fields
	//
	//*************************************************************************
	_varsRegex : /^prop|eVar[0-9]+$/i,
	
	
	
	//*************************************************************************
	//
	//	Methods
	//
	//*************************************************************************
	
	//
	//
	//
	TrackAction : function(actionName, vars, events)
	{
		//this.TrackCustomLink(this, actionName, vars, events);
		
		var args = this._BuildLinkArgs(vars, events);
		this.TrackPageView(actionName, args);
	},
	
	
	//
	//	...
	//	
	//	obj:		...
	//	linkName:	...
	//	vars:		Dictionary of variables to pass to Omniture. It can 
	//				contains either props or eVars.
	//				ie.: {prop1:"value", prop2:"value", eVars2:"value"}
	//				If the value of the var is null, then the global value
	//				(from the page's js) is used.
	//	events:		Array of event name that Omniture must track.
	//				ie.: ["event1", "event3", "event16"]
	//
	TrackCustomLink : function(obj, linkName, vars, events)
	{
		var args = this._BuildLinkArgs(vars, events);
		
		// Send data to Omniture
		this.TrackLink(obj, "o", linkName, args);
	},
		
	//
	//	...
	//
	TrackDownloadLink : function(obj, linkName, vars, events)
	{
		var args = this._BuildLinkArgs(vars, events);
		
		// Send data to Omniture
		this.TrackLink(obj, "d", linkName, args);
	},
	
	//
	//	...
	//
	TrackExitLink : function(obj, linkName, vars, events)
	{
		var args = this._BuildLinkArgs(vars, events);
		
		// Send data to Omniture
		this.TrackLink(obj, "e", linkName, args);
	},
	
	
	//
	//	...
	//
	TrackLink : function(obj, linkType, linkName, args)
	{
		if (typeof(s_gi) != "undefined")
		{
			var s = s_gi(s_account);
			
			// Append all the args to "s".
			for (var key in args)
			{
				s[key] = args[key];
			}
			
			// Send data to Omniture
			s.tl(obj, linkType, linkName);
		}
	},
	
	
	//
	//	...
	//
	TrackPageView : function(pageName, args)
	{
		if (typeof(s_gi) != "undefined")
		{
			var s = s_gi(s_account);
			
			s.pageName = pageName;
			
			// Append all the args to "s".
			for (var key in args)
			{
				s[key] = args[key];
			}
			
			// Send data to Omniture
			s.t();
		}
	},
	
	
	
	//*************************************************************************
	//
	//	Private API
	//
	//*************************************************************************

	//
	//	...
	//
	_BuildLinkArgs : function(vars, events)
	{
		var args = {};
		
		
		// Add infos to "s".
		args.linkTrackVars = this._BuildLinkTrackVars(vars, events);
		
		// Add the events to "s".
		if (events && events.length)
		{
			args.linkTrackEvents = events.join(",");
			args.events = events.join(",");
		}
		
		// Add the vars to "s".
		for (var key in vars)
		{
			if (this._varsRegex.test(key))
			{
				if (vars[key] != null)
					args[key] = vars[key];
			}
		}


		return args;
	},
	
	
	//
	//	...
	//
	_BuildLinkTrackVars : function(vars, events)
	{
		var items = [];
		
		
		// Check if we must track events.
		if (events && events.length)
			items[items.length] = "events";
			
		// Check if we must track vars.
		for (var key in vars)
		{
			if (this._varsRegex.test(key))
				items[items.length] = key;
		}
		
		
		return items.join(",");
	}
	
};

Unyk.Common.Omniture = new Unyk.Common.Omniture();

//
//	Shorthands
//
var Omniture = Unyk.Common.Omniture;



//*****************************************************************************
//
//	Viadeo Bar Handler
//
//*****************************************************************************

//
//	...
//	Note: Viadéo bar init handler
//
Unyk.Common.AddViadeoBarHandler = function()
{
	if (!$("viadeo-login"))
		return; //No control element found exit.

	var whatIsViadeoPopup = null;
	var ws = new Unyk.Web.WebServiceProxy();
	ws._ExecuteCommand("/events/viadeo", "init-bar", true, null, {
		success: function(o)
		{
			var configs = JSON.parse(o.responseText);
			if (configs.loginUrl != "")
			{
				// Set the href of the viadeo login link.
				var viadeoLoginLink = $("viadeo-login");
				if (viadeoLoginLink)
				{
					viadeoLoginLink.href = configs.loginUrl;
					Event.on(viadeoLoginLink, "click", function(e, args) {
						Omniture.TrackPageView("Go to Viadeo - Bar");
					});
				}

				$("go-to-viadeo-label").innerHTML = configs.goToViadeoLabel;


				// Bind the "What is Viadeo" link in the UNYK menu bar.
				var menulink = $("what-is-viadeo-menu-link");
				if (menulink)
					menulink.href = configs.whatIsViadeoLink;

				// Bind the "What is Viadeo" link in the UNYK menu bar.
				var viadeoProfileLink = $("viadeo-my-profile");
				if (viadeoProfileLink)
					viadeoProfileLink.href = configs.ViadeoProfileLink;


				// Bind the What is Viadeo click event. (the one in the Viadeo bar).
				Event.removeListener("what-is-viadeo", "click"); // LOLhack: see Cribe for details.
				Event.on("what-is-viadeo", "click", function(e, args)
				{
					Unyk.Common.DisplayWhatIsViadeoPopUp();
				});


				// Display the "What is Unyk / What is Viadeo" popup for the users who did not see it already.
				var cookie = YAHOO.util.Cookie.get("WhatIsViadeoPopup");
				if (cookie == "1")
				{
					// Show the bar normally.
					Dom.setStyle("viadeo-bar", "top", "0");

					Unyk.Common.DisplayWhatIsViadeoPopUp();
				}
				else
				{
					if (YAHOO.util.Cookie.get("viadeo-gateway"))
					{
						// If the cookie exists, show the bar normally.
						Dom.setStyle("viadeo-bar", "top", "0");
					}
					else
					{
						// Cookie doesn't exists: use the spiffy animation!
						var nextDate = new Date();
						nextDate.setDate(nextDate.getDate() + 30);
						YAHOO.util.Cookie.set("viadeo-gateway", "done", { path: "/", expires: nextDate });
						var anim = new YAHOO.util.Anim("viadeo-bar", { top: { from: -29, to: 0} }, 1.5, YAHOO.util.Easing.easeOut);
						anim.animate();
					}
				}
			}
		},
		cache: false
	});
}


Unyk.Common.DisplayWhatIsViadeoPopUp = function()
{
	var whatIsViadeoPopup = null;
	var ws = new Unyk.Web.WebServiceProxy();
	ws._ExecuteCommand("/events/viadeo", "what-is-viadeo", true, { l: "internal" }, {
		success: function(o)
		{
			var html = JSON.parse(o.responseText);
			if (whatIsViadeoPopup == null)
			{
				whatIsViadeoPopup = new YAHOO.widget.Panel(
					"wiv",
					{
						width: "69.23em",
						fixedcenter: true,
						close: true,
						draggable: false,
						zindex: 4,
						modal: true,
						visible: false
					}
				);
			}

			whatIsViadeoPopup.setHeader(html.header);
			whatIsViadeoPopup.setBody(html.body);
			whatIsViadeoPopup.setFooter(html.footer);
			whatIsViadeoPopup.render(document.body);

			Event.on("continue-on-viadeo", "click", function(e, args)
			{
				Omniture.TrackPageView("Go to Viadeo - Popup");
			});
			Event.on("what-is-viadeo-go-unyk", "click", whatIsViadeoPopup.hide, null, whatIsViadeoPopup);

			whatIsViadeoPopup.show();

			// Remove the cookie (change it's value since YUI does not seems to be able to remove a cookie he didn't set).
			if (window.location.host.indexOf(".unyk.com") > -1)
			{
				// PROD
				YAHOO.util.Cookie.set("WhatIsViadeoPopup", "0", { path: "/", domain: ".unyk.com" });
			}
			else
			{
				// DEV
				YAHOO.util.Cookie.set("WhatIsViadeoPopup", "0", { path: "/", domain: window.location.host });
			}
		},
		cache: false
	});
}
