﻿/////////////////////////////////////////////////////////////////////////////////
// Cossette base lib
/////////////////////////////////////////////////////////////////////////////////
var Cossette = Cossette || {
	globals: {},
	
	init: function(){
		
		if(arguments)
			for(var i = 0; i < arguments.length; i++){
				this['_init' + arguments[i]]();	
			}	
		
	},
	
	_initPlaceHolder: function(){
		/* add placeholder behavior for unsupported browser */
		var i = document.createElement('input');
		if(!('placeholder' in i)){
			$('input[placeholder]').bind({
				'focus': function(){
					var me = $(this);
					if(me.val() == me.attr('placeholder'))
						me.val('');
				},
				'blur': function(){
					var me = $(this);
					if(me.val() == '' && me.attr('placeholder') != 'undefined')
						me.val('' + me.attr('placeholder'));
				}
			}).each(function(){ this.value = this.placeholder; });
		}
	}
	
};

Date.Months = {
	Names: {
		'fr':['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		'en':['January','February','March','April','May','June','July','August','September','October','November','December']
	},
	Abbrev: {
		'fr':['janv.','fevr.','mars','avr.','mai','juin','juill.','août','sept.','oct.','nov.','déc.'],
		'en':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']
	}
};

/*--- Cossette.Extensions (executes on load) ------*/
Cossette.Extensions = Cossette.Extensions || {};
Cossette.Extensions.Arrays = function(){
	if (typeof Array.prototype.indexOf == 'undefined'){
		Array.prototype.indexOf = function(obj) {
			for (var i = 0; i < this.length; i++)
				if (this[i] == obj) { return i; }
			return -1;
		};
	}
}();
Cossette.Extensions.Date = function(){
	Date.prototype.getMonthName = function(culture){
		var m = this.getMonth();
		culture = (culture || typeof Cossette.Context != 'undefined' ? Cossette.Context.culture : 'fr');	
		return Date.Months.Names[culture][m];
	};
	Date.prototype.getMonthAbbrev = function(culture){
		var m = this.getMonth();
		culture = (culture || typeof Cossette.Context != 'undefined' ? Cossette.Context.culture : 'fr');	
		return Date.Months.Abbrev[culture][m];
	};
	Date.prototype.weekRange = function(){
		var r = {start: null, end: null};
		var d = this.getDay();
		r.start = d == 0
			? this
			: new Date(this.getTime() - (d * 24 * 60 * 60 * 1000));
		r.end = d == 6
			? this
			: new Date(this.getTime() + ((6 - d) * 24 * 60 * 60 * 1000));
		if(r.end.getDay() == 5)
			r.end = new Date(r.end.getTime() + (60 * 60 * 1000));
		if(r.end.getDay() === 0)
			r.end = new Date(r.end.getTime() - (60 * 60 * 1000));
		return r;
	}
	Date.prototype.addWeeks = function(numberOfWeeks){
		var r = null;
		r = new Date(this.getTime() + (((7 * numberOfWeeks) - this.getDay()) * 24 * 60 * 60 * 1000));
		if(r.getDay() == 6)
			r = new Date(r.getTime() + (60 * 60 * 1000));
		return r;
	}
	Date.prototype.toSimpleString = function(){
		return this.getFullYear() + '-' + (this.getMonth() < 10 ? '0' + (this.getMonth() + 1) : this.getMonth() + 1) + '-' + this.getDate();
	}
}();
Object.isArray = function(object){
	return (object != null && typeof object == 'object' && object.length != undefined);
};
String.isNullOrEmpty = function(string){
	return typeof string == 'undefined' || string === null || string === '';
};
Date.parseFromDotNet = function(string){
	return new Date(new Number(string.replace(/[^0-9]+/g, "")));
};
String.format = function(format){
	if(arguments.length <= 1)
		return format;
	for(var i=1; i < arguments.length; i++)
		format = format.replace('{'+ (i-1) +'}', arguments[i]);
	return format;
};

/* Fields object
 * Utiliser pour storer les informations en/fr
------------------------------------------------------------------ */
Cossette.Fields = function(fields){
	var self = this;
	self._fields = fields || {};
};

Cossette.Fields.prototype.g =
Cossette.Fields.prototype.get = function(name, culture){
	var self = this;
	culture = culture || (Cossette.Context != undefined ? Cossette.Context.culture : 'fr');
	return typeof self._fields[name] == 'object'
			? self._fields[name][culture]
			: self._fields[name];
};

Cossette.Fields.prototype.s =
Cossette.Fields.prototype.set = function(name, value, culture){
	var self = this;
	culture = culture || (Cossette.Context != undefined ? Cossette.Context.culture : 'fr');
	if(typeof self._fields[name] == 'object'){
		self._fields[name][culture] = value;		
	}
	else 
		self._fields[name] = value;
};

Cossette.Fields.prototype.all = function() {
	var self = this;
	return self._fields;
};

/*--- Cossette.Keys (mapping of some keys' name with their value) ------*/
Cossette.Keys = {
	LEFT:37,
	UP:38,
	DOWN:40,
	RIGHT:39,
	ENTER:13,
	BACKSPACE:8
};

/*--- Cossette.Utility ------*/
Cossette.Utility = {
	parseDateAndTime: function(format, value){
		var d = $.datepicker.parseDate(format, value);
		var t = value.substr(value.indexOf('T') + 1);
		var h = new Number(t.substring(0,2));
		var m = new Number(t.substring(2,2));
		d.setHours(h);
		d.setMinutes(m);
		return d;
	},
	extend: function(){
		var results = {};
		for (var i=0, l=arguments.length; i < l; i++)
			for (var prop in arguments[i])
				results[prop] = arguments[i][prop];
		return results;
	},
	supportCSSProperty: function(propName, element) {
		element = element || document.documentElement;
		var prefixes = ['Moz', 'Webkit', 'Khtml', 'O', 'Ms'];
		var style = element.style,
				prefixed;

		// test standard property first
		if (typeof style[propName] == 'string') return true;

		// capitalize
		propName = propName.charAt(0).toUpperCase() + propName.slice(1);

		// test vendor specific properties
		for (var i=0, l=prefixes.length; i<l; i++) {
			prefixed = prefixes[i] + propName;
			if (typeof style[prefixed] == 'string') return true;
		}
		return false;
	}
};

/*--- Cossette.Config ------*/
Cossette.Config = {
	cultureParam: 'l',
	serviceURI: '',
	resourcesPath: 'resources/',
	assetsPath: 'assets/',
	dbName: 'Cossette',
	useDatabase:false
};

/*--- Cossette.Context ------*/
Cossette.Context = {
  culture: 'fr', /* en | fr */
	path: '', /* application path */
	UA: null, /* user agent components */
	isIOS: function(){
		var rx = /(iPad|iPhone)/i;
		return rx.test(navigator.platform);
	}
};

/*--- Cossette.Url ------*/
Cossette.Url = {
	location: function(uri, params) {
		document.location = this.uri(uri, params);
  },
	pathname: function(keepExtension){
		if (typeof keepExtension == 'undefined') 
			keepExtension = true;
		var p = location.pathname;
		var i, ei = -1;
		if((i = p.lastIndexOf('/')) > -1)
			p = p.substr(i + 1);
		if(!keepExtension)
			if((ei = p.lastIndexOf('.')) > -1)
				p = p.substr(0, ei);
		return p;
	},
	/* params: 'clear' pour vider les querystrings */
	uri: function(uri, params) {
		if (typeof (params) == 'undefined' || params == null)
			return uri;
		else {
			var urlparts = uri.split('?');
			if (typeof (params) == 'string' && params == 'clear')
				return urlparts[0];
			else if (urlparts.length > 1) {
				var kv = urlparts[1].split('&');
				var q = {};
				for (var p in kv) {
					var t = kv[p].split('=');
					q[t[0]] = t[1];
				}
				return urlparts[0] + '?' + $.param($.extend(q, params));
			}
			else
				return urlparts[0] + '?' + $.param(params);
		}
	},
	encodeArray: function(array, sep){
		if(!array.length)
			return '';
		var q = '';
		if(typeof sep == 'undefined')
			sep = ';';
		for(var i=0, l=array.length; i<l; i++)
			q += array[i] + sep;
		return q;
	},
	params: function(name) {
		var urlparams = location.search;
		var params = null;
		var singleValue = typeof (name) != 'undefined';
		if (urlparams.length > 1) {
			params = {};
			urlparams = urlparams.substr(1);
			var kv = urlparams.split('&');
			for (var p in kv) {
				var t = kv[p].split('=');
				if (singleValue && t[0] == name) return t[1];
				else params[t[0]] = t[1];
			}
		}
		return singleValue ? null : params;
	},
	img: function(path){
		return Cossette.Context.path + Cossette.Config.resourcesPath + 'img/' + path;
	}
};

/////////////////////////////////////////////////////////////////////////////////
// Cossette Tracking
/////////////////////////////////////////////////////////////////////////////////
Cossette.Tracking = {};

Cossette.GA =
Cossette.Tracking.GoogleAnalytics = {	
	METHOD: { PAGEVIEW: '_trackPageview', EVENT: '_trackEvent', CUSTOMVAR: '_setCustomVar' },
	_tracker: undefined,
	enabled: false,
	log: true,
	alert: false,
	config: { async:true },
	init: function(uaccount){
		var self = this;

		if(self.config.async && typeof window._gaq == 'undefined'){
			if(typeof uaccount == 'undefined')
				throw "Google Analytics UA undefined";
				
			window._gaq = window._gaq || [];
		  window._gaq.push(['_setAccount', uaccount]);
		  window._gaq.push(['_trackPageview']);

	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

		} else if(!self.config.async && typeof window._gat == 'undefined'){
			// todo
		}

		self._tracker = self.config.async
			? window._gaq : window._gat._createTracker(uaccount);
	},
	
	/*
		when method == METHOD.PAGEVIEW, no params are required
		when method == METHOD.EVENT, params should be an array with the following indexes :
		[0] = category (required)
			The name you supply for the group of objects you want to track.
		[1] = action (required)
			A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.
		[2] = label (optional)
			An optional string to provide additional dimensions to the event data.
		[3] = value (optional)
			An integer that you can use to provide numerical data about the user event.

		more details : http://code.google.com/intl/en/apis/analytics/docs/tracking/eventTrackerGuide.html
	*/
	track: function(method, params){
		var self = this;
		
		var action = typeof method != 'string'
			? self.METHOD.PAGEVIEW : method;
		var opts = typeof params == 'undefined' 
			? method : params;
		
		if(self.log && typeof console != 'undefined')
			console.log('will track method : ', action, ' with options : ', opts);
		else if(self.log || self.alert)
			alert('will track method : ' + action + ' with options : ' + opts);

		if(self.enabled && typeof self._tracker == 'object'){
			if(!self.config.async) self._tracker[action](opts); 
			else self._tracker.push([action].concat(opts));
		}
	}
};

/////////////////////////////////////////////////////////////////////////////////
// Cossette Social (wrappers for some social plugins)
/////////////////////////////////////////////////////////////////////////////////
Cossette.Social = {};

/* Twitter
-------------------------------------------- */
Cossette.Social.Twitter = {};

Cossette.Social.Twitter.Utility = {};

Cossette.Social.Twitter.Utility.parseTweetEntities = function(tweet) {
    // attention à l'ordre
    tweet = Cossette.Social.Twitter.Utility.parseURL(tweet);
    tweet = Cossette.Social.Twitter.Utility.parseHashtag(tweet);
    tweet = Cossette.Social.Twitter.Utility.parseUsername(tweet);
    return tweet;
};

Cossette.Social.Twitter.Utility.parseURL = function(tweet) {
    return tweet.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
        return '<a target="_blank" href="' + url + '">'+url+'</a>';
    });
};

Cossette.Social.Twitter.Utility.parseUsername = function(tweet) {
    return tweet.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
        var username = u.replace("@", "")
        return '<a target="_blank" href="http://twitter.com/' + username + '">'+u+'</a>';
    });
};

Cossette.Social.Twitter.Utility.parseHashtag = function(tweet) {
    return tweet.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
        var tag = t.replace("#", "%23")
        return '<a target="_blank" href="http://search.twitter.com/search?q="' + tag + '">'+t+'</a>'; 
    });
};

Cossette.Social.Twitter.TweetButton = function(selector, params){
	if(typeof selector == 'string')
		selector = $(selector);
	
	var opts = Cossette.Utility.extend(Cossette.Social.Twitter.TweetButton.DefaultsOptions, params);
	
	if(opts.culture == '')
		opts.culture = Cossette.Context.culture;
	
	selector.attr({
		'href': 'http://twitter.com/share',
		'class': 'twitter-share-button',
		'data-count': opts.type,
		'data-lang': opts.culture
	}).text('Tweet');
	
	if(opts.tweetText != '')
		selector.attr({'data-text': opts.tweetText});
	if(opts.tweetUrl != '')
		selector.attr({'data-url': opts.tweetUrl});
	
	if(typeof window.twttr != 'object'){
		var e = document.createElement('script');
		e.src = 'http://platform.twitter.com/widgets.js';
		document.body.appendChild(e);
	}
	
};

Cossette.Social.Twitter.TweetButton.Type = {
	VERTICAL:'vertical', /* 65px x 62px */ 
	HORIZONTAL:'horizontal', /* 110px x 20px */
	NO_COUNT:'none' /* 65px x 20px */
};

Cossette.Social.Twitter.TweetButton.DefaultsOptions = {
	type: Cossette.Social.Twitter.TweetButton.Type.NO_COUNT,
	tweetText:'',
	tweetUrl:'',
	culture:'',
	mentionedAccount: '',
	relatedAccount:'',
	relatedAccountDescription:''
};

Cossette.Social.Flickr = {};

Cossette.Social.Flickr.PhotoSizes = {
	/*small square 75x75*/
	xxsmall: "s",
	/*thumbnail, 100 on longest side*/
	thumbnail: "t",
	/*small, 240 on longest side*/
	xsmall: "m",
	/*medium, 500 on longest side*/
	small: "-",
	/*medium 640, 640 on longest side*/
	medium: "z",
	/*large, 1024 on longest side**/
	large: "b",
	/*original*/
	original: "o"
};

Cossette.Social.Flickr.Url = {};

Cossette.Social.Flickr.Url.photo = function(farmid, serverid, id, secret, photo_size, format){
	return 'http://farm'+farmid+'.static.flickr.com/'+serverid+'/'+id+'_'+secret+'_'+photo_size+'.'+ (format || 'jpg');
};

Cossette.Social.Flickr.Feed = {};

Cossette.Social.Flickr.Feed._call = function(url, data, cb){
	
	$.ajax({
		"url": url,
		"data": data,
		"dataType": "json",
		"success": function(data, textStatus, jqXHR){
			cb(data);
		}
	});

};	

Cossette.Social.Flickr.Feed.public = function(args, cb){
	Cossette.Social.Flickr.Feed._call(
		"http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
		$.extend({
			"id": -1,
			"ids": "",
			"tags": "",
			"tagmode": "all",
			"format": "json",
			"lang": ((typeof Cossette.Context == "object" 
							? Cossette.Context.culture == "fr" 
								? "fr-fr"
								: "en-us"
							: false) || "fr-fr")
		}, args),
		cb
	);
};

Cossette.Social.Flickr.Feed.friends = function(args, cb){
	
	Cossette.Social.Flickr.Feed._call(
		"http://api.flickr.com/services/feeds/photos_friends.gne?jsoncallback=?",
		$.extend({
			"user_id": -1,
			"display_all": 0,
			"friends": 0,
			"format": "json",
			"lang": ((typeof Cossette.Context == "object" 
							? Cossette.Context.culture == "fr" 
								? "fr-fr"
								: "en-us"
							: false) || "fr-fr")
		}, args),
		cb
	);

};
