/**
 * Youfoot application wide Javascript namespace
 * 
 */
var YouFoot = {};

YouFoot.init = function (){
	for (var prop in this) {
		if (typeof this[prop].init == 'function') {
			if (this[prop].require != undefined) {
				var classes = this[prop].require.slice();
				classes.push(this[prop].init.bind(this[prop]));
				YouFoot.use.apply(window, classes);
			} else {
				this[prop].init();
			}
		}
	}
};

//
// Load any number of class objects from the classes dir 
// loads files asynchronously.
//
// Appends script tags to the document head.
//
// Example. YouFoot.use('MultiForm', 'Template', function () { .. });
// This will load MultiForm and Template classes and when they are done run the callback.
//
//
YouFoot.use = function () {
	function _appendScript(filename, callback) {
		var head = document.getElementsByTagName("head")[0];
		var script = document.createElement("script");
		script.src = filename;
		var done = false;
      
		script.onload = script.onreadystatechange = function () {
			if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) {
				done = true;
				callback();
			}
		}
		head.appendChild(script);
	}

	var compressorPath = window.basePath + 'asset_compress/js_files/join/';

	var classDir = window.basePath + 'js/classes/';
	var args = jQuery.makeArray(arguments);
	var readyCallback = Class.empty;

	if (typeof args[args.length -1] == 'function') {
		readyCallback = args.pop();
	}

	var filename = compressorPath + args.join('/');
	_appendScript(filename, readyCallback);
};


/**
 * i18n Object for JS translations
 *
 */
YouFoot.i18n = (function() {
	
	var _i18nDict = {};
	var i18n = {  
	/**
	 * get a translated string from the translations dictionary
	 * @param [string] stringName name of string you want.
	 * @returns [string] Value of translated string
	 */
		get : function(stringName,callback){
			$.each(_i18nDict,function (i,val){
			//	alert(_i18nDict[i])
				//alert(i+ ',' +val + '  ');
				
			});
			/* $.ajax({
			url:"/translates/javascripti18nRequest",
			type:"POST",	
			async:false,	
			cache:true,
			data:{
				"data[translates][phrase]":phrase
			},
			dataType:"text",
			success:function(data){
				//callback.call(this,data);						
				 phrase  = data;
		    }
		});	*/	   	  
			if (_i18nDict[stringName]) {
				return _i18nDict[stringName];
			}
				//Check for the phrase @app/views/elements/layout/javascript_i18n.ctp	
			        stringNameText = $("#hidden_phrases span[name = "+stringName+"]").text();
			        //stringNameText = stringNameText.trim();
			        
			        //This line added by Nirmal as trim function was not working on IE
			        stringNameText = $.trim(stringNameText);
					stringName = (stringNameText == "")?stringName:stringNameText;	
 			return stringName;     
		},
	/**
	 * Set a value(s) to the dictionary.
	 * 
	 * @param [mixed] stringName either the stringname or a dictionary (object literal) to append
	 * @param [string] value Value of the stringname being added.
	 */
		set : function(stringName, value) {
			if (typeof(stringName) === 'string') {
				_i18nDict[stringName] = value;
			} else if (value === undefined) {
				for (var key in stringName) {
					_i18nDict[key] = stringName[key];
				} 
			}
		}
	}
	return i18n;
})();

var __ = YouFoot.i18n.get;

YouFoot.Templates = {};


/**
 * Create a basic prototypal inheritance Class.
 * 
 * Create new classes with Class.create({prototype object});
 * Extend a class with Class.extend({prototype object});
 * Tape on new methods to all existing instances with Class.implement({object});
 * 
 * Classes can have an init() function which acts as a constructor for the prototype
 */
function Class (features) {
	var klass = function (noStart) {
		if (typeof this.init == 'function' && noStart != 'noInit') {
			return this.init.apply(this, arguments);
		}
		return this;
	};
	for (var key in this) {
		klass[key] = this[key];
	}
	klass.prototype = features;
	return klass;
};

Class.prototype.extend = function (features) {
	var oldProto, oldFunc, newFunc, func;
	oldProto = new this('noInit');

	var makeParent = function(parent, current) {
		return function () {
			this.parent = parent;
			return current.apply(this, arguments);
		};
	};

	for (var key in features) {
		oldFunc = oldProto[key];
		newFunc = features[key];
		if (typeof oldFunc != 'function' || typeof newFunc != 'function') {
			func = newFunc;
		} else {
			func = makeParent(oldFunc, newFunc);
		}
		oldProto[key] = func;
	}
	return new Class(oldProto);
};

Class.prototype.implement = function (features) {
	for (var key in features) {
		this.prototype[key] = features[key];
	}
};

/**
 * Empty function good for comparing to empty functions
 */
Class.empty = function () { };



/**
 * Add bind function to all functions.
 *
 * lets change 'this' in any function.
 */
if (typeof Function.bind != 'function') {
	Function.prototype.bind = function (obj) {
		var method = this;
		return function() {
			return method.apply(obj, arguments);
		};
	}
}

// Convert CamelCase string to camel_case string.
if (typeof String.underscore != 'function') {
	String.prototype.underscore = function () {
		var underscored = this.replace(/([A-Z])/g, '_$1').toLowerCase();
		if (underscored.substr(0, 1) == '_') {
			return underscored.substring(1);
		}
		return underscored;
	}
}


YouFoot.alerts = {
	init : function() {
		if ($.fn.jqm == undefined) {
			return;
		}
		$('#alert').jqm({overlay: 40, modal : true, trigger : false});
		$('#confirm').jqm({overlay: 40, modal : true, trigger : false});
		$('.dialogClose').click(function(){
			$('#alert').jqmHide();
		});
	}
};

YouFoot.alert = function (msg, content) {
	$('#alert').jqmShow()
		.removeClass('error')
		.find('h2').html(msg)
		.end()
		.find('p').empty().html(content);
};

YouFoot.error = function (msg, content) {
	$('#alert').jqmShow()
		.addClass('error')
		.find('h2').html('<span>' + msg + '</span>')
		.end()
		.find('p').empty().html(content);
};

YouFoot.confirm = function (msg, callback, options) {
	if (options.yesValue) {
		$('#confirm .confirm-yes input').val(options.yesValue);
	}
	if (options.noValue) {
		$('#confirm .confirm-no input').val(options.noValue);
	}

	$('#confirm')
		.jqmShow()
		.find('p.message').html(msg)
		.end()
		.find(':submit:visible').unbind('click').bind('click', function (event) {
			if (this.value == $('#confirm .confirm-yes input').val()) {
				if (typeof callback == 'string') {
					window.location.href = callback;
				} else {
					callback();
				}
			}
			$('#confirm').jqmHide();
			return false;
		});
};
YouFoot.inlineTranslation = {
		//var eventObject,			
		createPopup : function (e,data){
		    //getting height and width of the message box
		    var height = $('.translation_box').height();
		    var width = $('.translation_box').width();
		    //calculating offset for displaying popup message		    
			leftVal=e.pageX;
		    topVal=e.pageY;
		    if(leftVal < 0){
		    	leftVal = '0px';
		    }else leftVal = leftVal+5+'px';
		    if(topVal < 0){
		    	topVal = '0px';
		    }else topVal = topVal+15+'px';
		    //if(height<=132){topVal = topVal+78.5+"px"}else topVal = topVal+130+"px";
		    //show the popup message and hide with fading effect
		    $('.translation_box').css({left:leftVal,top:topVal}).show();
	     },
		calcPopup : function (){
		    alert('popup');
	    }
};


/** Match ruleset object **/

YouFoot.MatchRuleSet = (function(ruleType){
	switch (ruleType){
	   case 'futsal':		  
		   return {
			    'name' : 'Futsal',
				'periods' : 2,
				'duration' : 20,
				'extraPeriods' : 2,
				'extraDuration' : 5,
				'additionalTime' : 15,
				'noOverlap' : 60,
				'playersPerTeam' : 5,
				'minDuration' : 40
		   }
	       break;
	   case 'standard_outdoor':
		   return {
				'name' : 'Standard Outdoor',
				'periods' : 2,
				'duration' : 45,
				'extraPeriods' : 2,
				'extraDuration' : 15,
				'additionalTime' : 15,
				'noOverlap' : 120,
				'playersPerTeam' : 11,
				'minDuration' : 90				
		   }
		   break;
	   case 'indoor_professional':
		   return {
			   	'name' : 'Indoor (Professional)',
				'periods' : 4,
				'duration' : 15,
				'extraPeriods' : 1,
				'extraDuration' : 15,
				'additionalTime' : false,
				'noOverlap' : 60,
				'playersPerTeam' : 6,
				'minDuration' : 60
		   }
		   break;
	   case 'indoor_novice':
		   return {
			    'name' : 'Indoor (Novice)',
				'periods' : 2,
				'duration' : 25,
				'extraPeriods' : 0,
				'extraDuration' : 0,
				'additionalTime' : false,
				'noOverlap' : 60,
				'playersPerTeam' : 6,
				'minDuration' : 50
		   }
		   break;
	   case 'beach':
		   return {
			    'name' : 'Beach',
				'periods' : 3,
				'duration' : 12,
				'extraPeriods' : 1,
				'extraDuration' : 3,
				'additionalTime' : false,
				'noOverlap' : 60,
				'playersPerTeam' : 5,
				'minDuration' : 36
		   }
		   break;
	   case 'custom':
		   return {
			    'name' : 'Custom',
				'periods' : 1,
				'duration' : 10,
				'extraPeriods' : 0,
				'extraDuration' : 0,
				'additionalTime' : false,
				'noOverlap' : 60,
				'playersPerTeam' : 0,
				'minDuration' : 5
		   }
		   break;
	}
});




/**
 * DATETWEEK OBJECT
 * datetweek.timeDifference(){
 * get difference of two dates
 * @params:laterdate,earlierdate
 * @return:daysDifference, hoursDifference, minutesDifference, secondsDifference;
 * @return type:array
 * }
 * datetweek.getGMTTime(){
 * get GMT time for local time
 * @params:offset('+1.0','-1.3' etc...), d (local time)
 * return locattime to GMT date
 * return type: date object
 * }
 * datetweek.timeZoneList(){
 * Fetch TimeZone
 * @params:zoneId
 * @return type:string
 * }
 * datetweek.compare(a,b){
 * Returns a number:
 * -1 if a < b
 * 0 if a = b
 * 1 if a > b
 * NaN if a or b is an illegal date
 * }
 * datetweek.inRange (d,start,end){
 * Returns a boolean or NaN:
 * true if d is between the start and end (inclusive)
 * false if d is before start or after end.
 * NaN if one or more of the dates are illegal.
 * }
 * datetweek.convert(){
 * Used by the other functions to convert their input to a date object. The input can be
 * a date-object : The input is returned as is.
 * an array: Interpreted as [year,month,day]. NOTE month is 0-11.
 * a number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
 * a string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
 * an object: Interpreted as an object with year, month and date attributes. NOTE month is 0-11.
 * }
 */


YouFoot.datetweek = (function() {
var datetweek = {
	    convert:function(d) {
	        return (
	            d.constructor === Date ? d :
	            d.constructor === Array ? new Date(d[0],d[1],d[2]) :
	            d.constructor === Number ? new Date(d) :
	            d.constructor === String ? new Date(d) :
	            typeof d === "object" ? new Date(d.year,d.month,d.date) :
	            NaN
	        );
	    },
	    compare:function(a,b) {
	        return (
	            isFinite(a=this.convert(a).valueOf()) &&
	            isFinite(b=this.convert(b).valueOf()) ?
	            (a>b)-(a<b) :
	            NaN
	        );
	    },
	    inRange:function(d,start,end) {
	        return (
	            isFinite(d=this.convert(d).valueOf()) &&
	            isFinite(start=this.convert(start).valueOf()) &&
	            isFinite(end=this.convert(end).valueOf()) ?
	            start <= d && d <= end :
	            NaN
	        );
	    },
	    getGMTTime:function(offset) {
	        // create Date object for current location
	        d = new Date();
	       
	        // convert to msec
	        // add local time zone offset
	        // get UTC time in msec
	        utc = d.getTime() + (d.getTimezoneOffset() * 60000);
	       
	        // create new Date object for different city
	        // using supplied offset
	        nd = new Date(utc + (3600000*offset));
	       
	        // return time as a string
	       // return "The local time in " + city + " is " + nd.toLocaleString();
	        return nd;
	    },
	    timeDifference:function(laterdate,earlierdate) {
	  	  var difference = laterdate.getTime() - earlierdate.getTime();
	  	  var daysDifference = Math.floor(difference/1000/60/60/24);
	  	  difference -= daysDifference*1000*60*60*24
	  	  var hoursDifference = Math.floor(difference/1000/60/60);
	  	  difference -= hoursDifference*1000*60*60
	  	  var minutesDifference = Math.floor(difference/1000/60);
	  	  difference -= minutesDifference*1000*60
	  	  var secondsDifference = Math.floor(difference/1000);
	  	  var timeDiff = new Array();
	  	  timeDiff[0] = daysDifference;
	  	  timeDiff[1] = hoursDifference;
	  	  timeDiff[2] = minutesDifference;
	  	  timeDiff[3] = secondsDifference;
	  	  return timeDiff; 
	  },
	  timeZoneList:function (zoneId) {
			var $zoneList = new Array();
		    $zoneList['Kwajalein']= '(GMT-12:00) International Date Line West';
			$zoneList['Pacific/Midway']= '(GMT-11:00) Midway Island';
			$zoneList['Pacific/Samoa']= '(GMT-11:00) Samoa';
			$zoneList['Pacific/Honolulu']= '(GMT-10:00) Hawaii';
			$zoneList['America/Anchorage']= '(GMT-09:00) Alaska';
			$zoneList['America/Los_Angeles']= '(GMT-08:00) Pacific Time (US & Canada)';
			$zoneList['America/Tijuana']= '(GMT-08:00) Tijuana; Baja California';
			$zoneList['America/Denver']= '(GMT-07:00) Mountain Time (US & Canada)';
			$zoneList['America/Chihuahua']= '(GMT-07:00) Chihuahua';
			$zoneList['America/Mazatlan']= '(GMT-07:00) Mazatlan';
			$zoneList['America/Phoenix']= '(GMT-07:00) Arizona';
			$zoneList['America/Regina']= '(GMT-06:00) Saskatchewan';
			$zoneList['America/Tegucigalpa']= '(GMT-06:00) Central America';
			$zoneList['America/Chicago']= '(GMT-06:00) Central Time (US & Canada)';
			$zoneList['America/Mexico_City']= '(GMT-06:00) Mexico City';
			$zoneList['America/Monterrey']= '(GMT-06:00) Monterrey';
			$zoneList['America/New_York']= '(GMT-05:00) Eastern Time (US & Canada)';
			$zoneList['America/Bogota']= '(GMT-05:00) Bogota';
			$zoneList['America/Lima']= '(GMT-05:00) Lima';
			$zoneList['America/Rio_Branco']= '(GMT-05:00) Rio Branco';
			$zoneList['America/Indiana/Indianapolis']= '(GMT-05:00) Indiana (East)';
			$zoneList['America/Caracas']= '(GMT-04:30) Caracas';
			$zoneList['America/Halifax']= '(GMT-04:00) Atlantic Time (Canada)';
			$zoneList['America/Manaus']= '(GMT-04:00) Manaus';
			$zoneList['America/Santiago']= '(GMT-04:00) Santiago';
			$zoneList['America/La_Paz']= '(GMT-04:00) La Paz';
			$zoneList['America/St_Johns']= '(GMT-03:30) Newfoundland';
			$zoneList['America/Argentina/Buenos_Aires']= '(GMT-03:00) Georgetown';
			$zoneList['America/Sao_Paulo']= '(GMT-03:00) Brasilia';
			$zoneList['America/Godthab']= '(GMT-03:00) Greenland';
			$zoneList['America/Montevideo']= '(GMT-03:00) Montevideo';
			$zoneList['Atlantic/South_Georgia']= '(GMT-02:00) Mid-Atlantic';
			$zoneList['Atlantic/Azores']= '(GMT-01:00) Azores';
			$zoneList['Atlantic/Cape_Verde']= '(GMT-01:00) Cape Verde Is.';
			$zoneList['Europe/Dublin']= '(GMT) Dublin';
			$zoneList['Europe/Lisbon']= '(GMT) Lisbon';
			$zoneList['Europe/London']= '(GMT) London';
			$zoneList['Africa/Monrovia']= '(GMT) Monrovia';
			$zoneList['Atlantic/Reykjavik']= '(GMT) Reykjavik';
			$zoneList['Africa/Casablanca']= '(GMT) Casablanca';
			$zoneList['Europe/Belgrade']= '(GMT+01:00) Belgrade';
			$zoneList['Europe/Bratislava']= '(GMT+01:00) Bratislava';
			$zoneList['Europe/Budapest']= '(GMT+01:00) Budapest';
			$zoneList['Europe/Ljubljana']= '(GMT+01:00) Ljubljana';
			$zoneList['Europe/Prague']= '(GMT+01:00) Prague';
			$zoneList['Europe/Sarajevo']= '(GMT+01:00) Sarajevo';
			$zoneList['Europe/Skopje']= '(GMT+01:00) Skopje';
			$zoneList['Europe/Warsaw']= '(GMT+01:00) Warsaw';
			$zoneList['Europe/Zagreb']= '(GMT+01:00) Zagreb';
			$zoneList['Europe/Brussels']= '(GMT+01:00) Brussels';
			$zoneList['Europe/Copenhagen']= '(GMT+01:00) Copenhagen';
			$zoneList['Europe/Madrid']= '(GMT+01:00) Madrid';
			$zoneList['Europe/Paris']= '(GMT+01:00) Paris';
			$zoneList['Africa/Algiers']= '(GMT+01:00) West Central Africa';
			$zoneList['Europe/Amsterdam']= '(GMT+01:00) Amsterdam';
			$zoneList['Europe/Berlin']= '(GMT+01:00) Berlin';
			$zoneList['Europe/Rome']= '(GMT+01:00) Rome';
			$zoneList['Europe/Stockholm']= '(GMT+01:00) Stockholm';
			$zoneList['Europe/Vienna']= '(GMT+01:00) Vienna';
			$zoneList['Europe/Minsk']= '(GMT+02:00) Minsk';
			$zoneList['Africa/Cairo']= '(GMT+02:00) Cairo';
			$zoneList['Europe/Helsinki']= '(GMT+02:00) Helsinki';
			$zoneList['Europe/Riga']= '(GMT+02:00) Riga';
			$zoneList['Europe/Sofia']= '(GMT+02:00) Sofia';
			$zoneList['Europe/Tallinn']= '(GMT+02:00) Tallinn';
			$zoneList['Europe/Vilnius']= '(GMT+02:00) Vilnius';
			$zoneList['Europe/Athens']= '(GMT+02:00) Athens';
			$zoneList['Europe/Bucharest']= '(GMT+02:00) Bucharest';
			$zoneList['Europe/Istanbul']= '(GMT+02:00) Istanbul';
			$zoneList['Asia/Jerusalem']= '(GMT+02:00) Jerusalem';
			$zoneList['Asia/Amman']= '(GMT+02:00) Amman';
			$zoneList['Asia/Beirut']= '(GMT+02:00) Beirut';
			$zoneList['Africa/Windhoek']= '(GMT+02:00) Windhoek';
			$zoneList['Africa/Johannesburg']= '(GMT+02:00) Johannesburg';
			$zoneList['Africa/Harare']= '(GMT+02:00) Harare';
			$zoneList['Asia/Kuwait']= '(GMT+03:00) Kuwait';
			$zoneList['Asia/Riyadh']= '(GMT+03:00) Riyadh';
			$zoneList['Asia/Baghdad']= '(GMT+03:00) Baghdad';
			$zoneList['Africa/Nairobi']= '(GMT+03:00) Nairobi';
			$zoneList['Asia/Tbilisi']= '(GMT+03:00) Tbilisi';
			$zoneList['Europe/Moscow']= '(GMT+03:00) Moscow';
			$zoneList['Europe/Volgograd']= '(GMT+03:00) Volgograd';
			$zoneList['Asia/Tehran']= '(GMT+03:30) Tehran';
			$zoneList['Asia/Muscat']= '(GMT+04:00) Muscat';
			$zoneList['Asia/Baku']= '(GMT+04:00) Baku';
			$zoneList['Asia/Yerevan']= '(GMT+04:00) Yerevan';
			$zoneList['Asia/Yekaterinburg']= '(GMT+05:00) Ekaterinburg';
			$zoneList['Asia/Karachi']= '(GMT+05:00) Karachi';
			$zoneList['Asia/Tashkent']= '(GMT+05:00) Tashkent';
			$zoneList['Asia/Kolkata']= '(GMT+05:30) Calcutta';
			$zoneList['Asia/Colombo']= '(GMT+05:30) Sri Jayawardenepura';
			$zoneList['Asia/Katmandu']= '(GMT+05:45) Kathmandu';
			$zoneList['Asia/Dhaka']= '(GMT+06:00) Dhaka';
			$zoneList['Asia/Almaty']= '(GMT+06:00) Almaty';
			$zoneList['Asia/Novosibirsk']= '(GMT+06:00) Novosibirsk';
			$zoneList['Asia/Rangoon']= '(GMT+06:30) Yangon (Rangoon)';
			$zoneList['Asia/Krasnoyarsk']= '(GMT+07:00) Krasnoyarsk';
			$zoneList['Asia/Bangkok']= '(GMT+07:00) Bangkok';
			$zoneList['Asia/Jakarta']= '(GMT+07:00) Jakarta';
			$zoneList['Asia/Brunei']= '(GMT+08:00) Beijing';
			$zoneList['Asia/Chongqing']= '(GMT+08:00) Chongqing';
			$zoneList['Asia/Hong_Kong']= '(GMT+08:00) Hong Kong';
			$zoneList['Asia/Urumqi']= '(GMT+08:00) Urumqi';
			$zoneList['Asia/Irkutsk']= '(GMT+08:00) Irkutsk';
			$zoneList['Asia/Ulaanbaatar']= '(GMT+08:00) Ulaan Bataar';
			$zoneList['Asia/Kuala_Lumpur']= '(GMT+08:00) Kuala Lumpur';
			$zoneList['Asia/Singapore']= '(GMT+08:00) Singapore';
			$zoneList['Asia/Taipei']= '(GMT+08:00) Taipei';
			$zoneList['Australia/Perth']= '(GMT+08:00) Perth';
			$zoneList['Asia/Seoul']= '(GMT+09:00) Seoul';
			$zoneList['Asia/Tokyo']= '(GMT+09:00) Tokyo';
			$zoneList['Asia/Yakutsk']= '(GMT+09:00) Yakutsk';
			$zoneList['Australia/Darwin']= '(GMT+09:30) Darwin';
			$zoneList['Australia/Adelaide']= '(GMT+09:30) Adelaide';
			$zoneList['Australia/Canberra']= '(GMT+10:00) Canberra';
			$zoneList['Australia/Melbourne']= '(GMT+10:00) Melbourne';
			$zoneList['Australia/Sydney']= '(GMT+10:00) Sydney';
			$zoneList['Australia/Brisbane']= '(GMT+10:00) Brisbane';
			$zoneList['Australia/Hobart']= '(GMT+10:00) Hobart';
			$zoneList['Asia/Vladivostok']= '(GMT+10:00) Vladivostok';
			$zoneList['Pacific/Guam']= '(GMT+10:00) Guam';
			$zoneList['Pacific/Port_Moresby']= '(GMT+10:00) Port Moresby';
			$zoneList['Asia/Magadan']= '(GMT+11:00) Magadan';
			$zoneList['Pacific/Fiji']= '(GMT+12:00) Fiji';
			$zoneList['Asia/Kamchatka']= '(GMT+12:00) Kamchatka';
			$zoneList['Pacific/Auckland']= '(GMT+12:00) Auckland';
			$zoneList['Pacific/Tongatapu']= '(GMT+13:00) Nukualofa';

		return $zoneList[zoneId];
		}
	}
  return datetweek;
})();




//
// Utility methods used in many places
//
var Utils = {
// Slide toggles an element, good for binding on click events
// ex. $(foo).bind('click', {text : 'one', textAlt : 'two', 'targetEl' : '#foo-bar'}, Util.toggleElement);
//
// @param string text Text state one
// @param string textAlt Text state two.
// @param string targetEl CSS selector for target to toggle.
//
	toggleElement : function(event) {
		var that = $(this);
		var selector = event.data.targetEl;
		var toggleText = function () {
			if (!event.data.text || !event.data.textAlt) {
				return;
			}
			if (that.text() == event.data.text) {
				that.text(event.data.textAlt);
			} else {
				that.text(event.data.text);
			}
		};
		$(selector).slideToggle('normal', toggleText);
		return false;
	}
};


var Validation = {
	notEmpty: function (value) {
		if (!value.length || value.length == 0) {
			return __('Must not be empty');
		}
		return true;
	},
	date: function (value) {
		if (!value.match(/(19|20)\d\d[- \/.](0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])/)) {
			return __('Must be a valid date');
		}
		return true;
	},
	url: function (value) {
		//from CakePHP Validation::url()
		var pattern = /^(?:(?:https?|ftps?|file|news|gopher):\/\/)?(?:(?:(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])|(?:[a-z0-9][-a-z0-9]*\.)*(?:[a-z0-9][-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,4}|museum|travel))(?::[1-9][0-9]{0,3})?(?:\/?|\/([\!\"\$\&\\\'\(\)\*\+\,\-\.\@\_\:\;\=\/0-9a-z]|(%[0-9a-f]{2}))*)?(?:\?([\!\"\$\&\\\'\(\)\*\+\,\-\.\@\_\:\;\=\/0-9a-z]|(%[0-9a-f]{2}))*)?(?:#([\!\"\$\&\\\'\(\)\*\+\,\-\.\@\_\:\;\=\/0-9a-z]|(%[0-9a-f]{2}))*)?$/i;
		if (!value.match(pattern)) {
			return __('Must be a valid url');
		}
		return true;
	}
};


if (console === undefined) {
	var console = {
		log: function () {},
		error: function () {},
		trace: function () {}
	};
}


/******
 * Permet de recuperer la position en pixel d'un objet DOM
 ******/
function findPos(obj) {
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
    }
    return {x:curleft,y:curtop};
}


/******
 * Permet de valider le format ISO d'une date (YYYY-MM-DD) 
 *****/
function ISODateValue(Str) { 
	var V, DObj = NaN
	V = Str.match(/^(\d{4})-(\d\d)-(\d\d)$/)
	if (V) V = (DObj=new Date(V[1], --V[2], V[3])).getMonth() == V[2]
	return !!V /* [Valid, DateObject] end ISODateValue */ 
}


/******
* Permet d'afficher la popup du Invite Friend
******/
function showInviteFriends(){	
	$.ajax({
		url:'/InviteFriends/find_friends',
		success:function(data){
			if(data.length > 0){
				$('#inviteFriend').show();
				$('#inviteOverlay').show();
				$('#inviteFriend').find('.contentForms').html(data);
				
				$.ajax({
					url:'/InviteFriends/suggest_friends',
					success:function(data){
						if(data.length > 0){
							$('#suggest_table').html(data);
							$('.group1').show();
							$('#more2').show();
						}
					}
				});
			}
		}
	});
}
	

function changefield(){	
	//corrige un bug de ie8 et ie7 => change le input en type='password'					
	document.getElementById("password-field").innerHTML = "<input type='password' class='left' id='SidebarLoginPasswd' tabindex='2' autocomplete='off' value='' name='data[User][passwd]'/>";
	document.getElementById("SidebarLoginPasswd").focus();
}

$(document).ready(function() {
	$('#UserAddForm input , #UserAddForm select').blur( function(){
		$('#tosAndPrivacy').hide();
		$('.facebook_connect').show();
		}
	);
	$('#UserAddForm input , #UserAddForm select').focus( function(){
		$('.facebook_connect').hide();
		$('#tosAndPrivacy').show();
		}
	);
	$('form').submit(function(){	
		var $class = $(':submit', this).attr('class');
		if($class != "login_btn"){
		 $(':submit', this).attr('disabled','true');
		}
	});	
});	


//Affiche la popup du Report Abuse
function reportAbuse(title, elemId){
	
	$.ajax({
		url:'/reports/abuseform/'+elemId,
		success:function(data){
			if(data == 'already'){
				$('.contentForms').html('Sorry !');
			}else{
				$('.contentForms').html(data);
				$('#reportAbuse .titleContent').html(title);
				$('#reportAbuse').css('border','3px solid red');
				$('#inviteOverlay').show();
				$('#reportAbuse').show();
				$('#reported_id').val(elemId);
			}
		}
	});
}

//Affiche la popup du Report Mistake
function reportMistake(title, elemId){
	$.ajax({
		url:'/reports/mistakeform',
		success:function(data){
			$('.contentForms').html(data);
			$('#reportAbuse .titleContent').html(title);
			$('#reportAbuse').css('border','3px solid green');
			$('#inviteOverlay').show();
			$('#reportAbuse').show();
			$('#reported_id').val(elemId);
		}
	});
}


//Envoi le report abuse
function sendReport(){
	
	if($.trim($('#ReportCategory').val()) == null){
		alert('category');
	}
	if($.trim($('#reportExplain').val()) == null){
		alert('explain');
	}
	
	if($.trim($('#ReportCategory').val()) != null && $.trim($('#reportExplain').val()) != null){
		
		var postData = {};
		postData.category = $('#ReportCategory').val();
		postData.explain = $('#reportExplain').val();
		postData.url = window.location.pathname;
		postData.content_reported_id = $('#reported_id').val();
		postData.type = $('.titleContent').html().toLowerCase();
		
		$.ajax({
			type : 'POST',
			data : postData,
			url : '/reports/add',
			dataType : 'json',
			cache:false,
			success : function(data) {
				if (data === true) {
					$('.title').html('Thank you for your report');
					$('.explain').html('We will review your report as soon as possible');
					$('.form').html('<div class="form-repor-button"><span class="button-discard" onclick="$(\'#reportAbuse\').hide();$(\'#inviteOverlay\').hide();"><input type="reset" value="Close"/></span></div>');
				}else{
					alert('error appear');
				}
			}
		});
	}
}
//Added on 24th October 2011 
$('.hasDatepicker').live('click',function(){
	  var div = $(this);
	  var  position = div.position();
	  $('#ui-datepicker-div').css('top', position.top);
});

