﻿var Claritin = Claritin || {};

/////////////////////////////////////////////////////////////////////////////////
// Page Controllers
/////////////////////////////////////////////////////////////////////////////////
Claritin.Master = {

	init: function() {
		var self = this;

		Cossette.Social.Facebook.parse();
		
		Cossette.Social.Facebook.onLike = function(){
			K7.GA.event('share', 'facebook', 'generic');
		};

		Cossette.Social.Twitter.TweetButton('a[rel=twitter]', { type: Cossette.Social.Twitter.TweetButton.Type.NO_COUNT });
		
		self.bindEvents();
	},

	/* attach events to dom elements */
	bindEvents: function() {
		/* footer links opening a popup */
		$(".lnkPopup").bind('click', function() {
			Cossette.CMS.CMServices.page(
					{ "nodeId": $(this).attr("data-NodeID") },
					function(page) {
						$('#dialog').css({ height: '400px', width: '800px' }).html(page.getItem('Content'))
							.attr("title", page.getItem('Title'))
							.dialog({ modal: true, height: 400, width: 800 });
					});
		});
		
		/* changing platform */
		$('#platformChange-bt').bind('click', function() {
			K7.GA.event('version', 'switch', 'to-mobile');
			setTimeout("window.location = '" + $(this).attr('href') + "'", 200);
			return false;
		});

		$('a[rel=external]').bind('click', function(){
			K7.GA.event('outbound', 'click', this.href);
			setTimeout("window.location = '" + this.href + "';", 200);
			return false;
		});
	}

};

Claritin.Home = {

	init: function(bannerProp) {
		var self = this;
		var c = new Claritin.Widget.Carousel('#mycarousel');

		self.bannerProperties = bannerProp;
		self.hasFlashSupport = typeof swfobject != 'undefined' && swfobject.hasFlashPlayerVersion('9');
		self.bannerIndex = 0;
		self.swf = undefined;

		self.render();
		self.showBanner(0);
		self.bindEvents();
	},

	render: function() {
		var self = this;
		var nav = $('#banner-nav');
		for (var i = 0, l = self.bannerProperties.length; i < l; i++)
			nav.append('<a href="javascript:;" class="selBanner"></a>');
	},

	bindEvents: function() {
		var self = this;

		$('.selBanner').bind('click', function() {
			self.showBanner($(this).index());
		});

	},

	nextBanner: function() {
		var self = this;
		var bannerCount = parseInt(self.bannerProperties.length, 10);
		self.bannerIndex = self.bannerIndex < bannerCount - 1
			? self.bannerIndex + 1 : 0;

		self.onBannerChange();
	},

	showBanner: function(index) {
		var self = this;
		var bannerCount = parseInt(self.bannerProperties.length, 10);

		index = parseInt(index, 10);

		self.bannerIndex = index < bannerCount
			? index : 0;

		self.onBannerChange();
	},

	_renderBanner: function() {
		var self = this;
		if (!self.hasFlashSupport)
			$('#flashID').html('<img src=' + self.bannerProperties[self.bannerIndex].imgUrl + ' alt="" />');
		else {
			var flashvars = { 
				videoUrl: self.bannerProperties[self.bannerIndex].videoUrl, 
				linkUrl:self.bannerProperties[self.bannerIndex].linkUrl,
				delay:7
			};
			swfobject.embedSWF(self.bannerProperties[self.bannerIndex].swfUrl, "flashID", "1000", "400", "10.0", "ressources/flash/expressInstall.swf",
				flashvars, {/*params*/ wmode: "transparent", bgcolor: "#000000", allowFullScreen:true }, {/*attributes*/}, function(e) {
					self.swf = e.ref;
				});
		}
	},

	onBannerChange: function() {
		var self = this;
		// change active dot
		$('.selBanner').eq(self.bannerIndex).addClass('active').siblings().removeClass('active');
		// call fadeOut function in the flash for smooth transition
		if (self.swf && typeof self.swf.fadeOut == 'function')
			self.swf.fadeOut();
		// the fadeOut lasts 1 second
		setTimeout(function() {
			self._renderBanner();
		}, 1000);
	}

};

Claritin.Product = {

	init: function(productName) {
		var c = new Claritin.Widget.Carousel('#mycarousel', { scroll: 1, wrap: 'both' });

		Cossette.Social.Facebook.onLike = function(){
			K7.GA.event('share', 'facebook', productName);
		};

		this.productName = productName;
		this.bindEvents();
	},

	bindEvents: function() {
		var self = this;
		$('.tag').bind('click', function() {
			K7.GA.event('coupon', 'produit', self.productName);
			K7.GA.pageview('download/click/' + this.href);
		});
	}

};

Claritin.ClaritinMobile = {
	
	init: function(title) {
		var self = this;
		Cossette.Social.Facebook.parse();

		Cossette.Social.Facebook.onLike = function(){
			K7.GA.event('share', 'facebook', 'mobile app');
		};

		Cossette.Social.Twitter.TweetButton('a[rel=twitter]', 
		{	type: Cossette.Social.Twitter.TweetButton.Type.NO_COUNT,
			tweetText: title });
		self.bindEvents();
	},
	
	bindEvents: function(){
		var self = this;
		$('.app-store > a').bind('click', function(){
			var me = $(this);
			K7.GA.pageview(document.location.pathname + document.location.search + (document.location.search.length>0?'&':'?') + 'goal=download_mobile_'+me.attr('class')+'_app');
			setTimeout("window.location = '" + me.attr('href') + "'", 200);
			return false;
		});
	}
	
};

Claritin.PollenReport = {

	init: function(opts, city, cities) {
		var self = this;

		self.opts = $.extend({ mapType: 'SMALL', mapID: '' }, opts);
		self.cities = cities;
		self.city = city;

		var callback = function(geoposition) {
			if (geoposition)
				self.city.Geoposition = {
					Longitude: geoposition.Longitude,
					Latitude: geoposition.Latitude
				};

			self.map = new Claritin.Map(
				{
					id: self.opts.mapID,
					markers: self.cities,
					activeMarker: self.city,
					mapType: self.opts.mapType,
					labels: self.opts.labels
				},
				{
					zoom: self.opts.mapType == 'SMALL' ? 11 : 4,
					center: geoposition ? new google.maps.LatLng(geoposition.Latitude, geoposition.Longitude) : new google.maps.LatLng(55, -94),
					mapTypeId: google.maps.MapTypeId.HYBRID,
					mapTypeControl: false,
					panControl: true,
					streetViewControl: true,
					zoomControlOptions: { style: google.maps.ZoomControlStyle.DEFAULT }
				}
			);

			self.bindEvents();
		}

		if (self.city != null)
			Claritin.Map.Geocoder.Geocode(self.city.Address, callback);
		else
			callback();

	},

	bindEvents: function() {



	}

};

/////////////////////////////////////////////////////////////////////////////////
// Widgets
/////////////////////////////////////////////////////////////////////////////////
Claritin.Widget = {};

/* Product carousel */
Claritin.Widget.Carousel = function(selector, options) {
	var self = this;

	self.opts = $.extend({}, Claritin.Widget.Carousel.DefaultOptions, options);

	self.carousel = $(selector).jcarousel(self.opts);
};

Claritin.Widget.Carousel.DefaultOptions = {
	vertical: false,
	wrap: null,
	scroll: 1
};

/* Menu, singleton */
Claritin.Widget.Menu = function(options) {
	var self = this;

	if (Claritin.Widget.Menu._instance != null) {
		delete this;
		return Claritin.Widget.Menu._instance;
	}

	self.bindEvents();

	Claritin.Widget.Menu._instance = self;
};

Claritin.Widget.Menu._instance = null;

Claritin.Widget.Menu.prototype.bindEvents = function() {
	var self = this;
	var flyby = $('nav.primary').find('li.products');
	var menuLinks = $('nav.primary ul li>a');

	menuLinks.bind('click', function() {
		var me = $(this);
		me.parent().toggleClass('active');
		menuLinks.not(me).parent().removeClass('active');
	}).hover(function() {
		var me = $(this);
		//menuLinks.not(me).parent().removeClass('active');
	});

	flyby.find('.banner').each(function() {
		var me = $(this);
		me.data({
			'background-image': me.css('background-image'),
			'description': me.find('.description').html()
		});
	});

	flyby.find('li').hover(function() {
		var me = $(this);
		var banner = me.closest('li.products').find('.banner');
		var html = me.find('.text').html();
		var img = $.trim(me.find('.img').text());
		banner.find('.description').removeClass('default').html(html);
		if (img != '')
			banner.css({ 'background-image': 'url(' + img + ')' });
	}, function() {
		var me = $(this);
		var banner = me.closest('li.products').find('.banner');
		banner.css({ 'background-image': banner.data('background-image') });
		banner.find('.description').addClass('default').html(banner.data('description'));
	});

};

/* Claritin Suggests */
Claritin.Widget.ClaritinSuggests = function(params) {
	var self = this;
	if (typeof Cossette.CMS != 'object')
		throw 'ClaritinSuggests is missing a component';

	self.resultItemModel = undefined;
	self.opts = $.extend({}, Claritin.Widget.ClaritinSuggests.DefaultOptions, params);
	self.itemHeight = 0;
	self.currentIndex = 0;
	self.count = 0;

	self.container = typeof self.opts.widgetContainer == 'string'
		? $(self.opts.widgetContainer) : self.opts.widgetContainer;

	self.submitButton = typeof self.opts.submitButton == 'string'
		? $(self.opts.submitButton) : self.opts.submitButton;

	self.form = self.container.find('.suggests-form');
	self.resultsContainer = self.form.siblings('.suggests-results');
	self.noresults = self.resultsContainer.children('.no-results');
	self.results = self.resultsContainer.children('.results')
		.wrap('<div class="results-wrapper"></div>')
		.wrap('<div class="results-container"></div>');

	self.resultsWrapper = self.resultsContainer.find('.results-wrapper');
	self.nextButton = $('<a href="javascript:;" class="down disabled"></a>').appendTo(self.resultsWrapper);
	self.prevButton = $('<a href="javascript:;" class="up disabled"></a>').appendTo(self.resultsWrapper);

	self.carousel = null;

	self.bindEvents();
};

Claritin.Widget.ClaritinSuggests.FindOptions = {
	age: '',
	symptoms: undefined,
	relief: ''
};

Claritin.Widget.ClaritinSuggests.DefaultOptions = {
	widgetContainer: '',
	submitButton: '',
	visible: 3,
	onSearch: null
};

Claritin.Widget.ClaritinSuggests.prototype.bindEvents = function() {
	var self = this;

	self.submitButton.bind('click', function() {
		var findOptions = self.validate();
		if (!findOptions) {
			self.form.find('.error').removeClass('hidden');
		} else {
			self.form.find('.error').addClass('hidden');
			self.find(findOptions, self.opts.onSearch);
		}
	});

	self.container.find('.restart').bind('click', function() {
		self.restart();
	});

	$('#suggestsAge, #suggestsRelief, input[type=checkbox].symptom').bind('change', function() {
		var f = self.gatherFindOptions();
		var me = $(this);
		if (me.val() != '')
			me.removeClass('error');
		if (me.hasClass('symptom') && f.symptoms.length > 0)
			$('#suggestsSymptoms').removeClass('error');
		if (f.age != '' && f.relief != '' && f.symptoms.length > 0) {
			self.form.find('.error').addClass('hidden');
			self.submitButton.removeClass('disabled');
		} else
			self.submitButton.addClass('disabled');
	});

	self.prevButton.bind('click', function() {
		var me = $(this);
		if (me.hasClass('disabled'))
			return;
		self.prevResults();
	});

	self.nextButton.bind('click', function() {
		var me = $(this);
		if (me.hasClass('disabled'))
			return;
		self.nextResults();
	});

};

Claritin.Widget.ClaritinSuggests.prototype.validate = function() {
	var self = this;
	var f = self.gatherFindOptions();
	var errors = false;
	if (f.symptoms.length == 0) {
		errors = true;
		$('#suggestsSymptoms').addClass('error');
	}

	if (f.age == '') {
		errors = true;
		$('#suggestsAge').addClass('error');
	}

	if (f.relief == '') {
		errors = true;
		$('#suggestsRelief').addClass('error');
	}
	return errors ? false : f;
};

Claritin.Widget.ClaritinSuggests.prototype.nextResults = function() {
	var self = this;

	if (self.currentIndex + 1 > self.count - self.opts.visible)
		self.currentIndex = 0;
	else
		self.currentIndex += 1;

	self.showResult();
};

Claritin.Widget.ClaritinSuggests.prototype.prevResults = function() {
	var self = this;

	if (self.currentIndex - 1 < 0)
		self.currentIndex = 0;
	else
		self.currentIndex -= 1;

	self.showResult();
};

Claritin.Widget.ClaritinSuggests.prototype.showResult = function() {
	var self = this;

	if (self.currentIndex < self.count - self.opts.visible)
		self.nextButton.removeClass('disabled');
	else
		self.nextButton.addClass('disabled');

	if (self.currentIndex > 0)
		self.prevButton.removeClass('disabled');
	else
		self.prevButton.addClass('disabled');

	self.results.animate({ top: '-' + (self.itemHeight * self.currentIndex) + 'px' },
		{ duration: 'normal',
			ease: 'easeInOut',
			queue: false
		});
};

Claritin.Widget.ClaritinSuggests.prototype.restart = function() {
	var self = this;
	self.form.show();
	self.resultsContainer.hide();
	self.results.css({ 'top': '0px' });
	self.nextButton.addClass('disabled');
	self.prevButton.addClass('disabled');
	self.currentIndex = 0;
	if (self.resultItemModel != undefined)
		self.results.empty();
};

Claritin.Widget.ClaritinSuggests.prototype.renderResults = function(pages) {
	var self = this;

	self.restart();

	self.form.hide();
	self.resultsContainer.show();
	self.count = pages.length;

	if (!pages.length) {
		self.resultsWrapper.hide();
		self.results.hide();
		self.noresults.show();
	} else {

		if (self.resultItemModel == undefined)
			self.resultItemModel = self.results.find('.item').eq(0).clone(false, false);

		self.results.find('.item').remove();

		var temp = $('<div></div>');
		for (var i = 0, l = pages.length; i < l; i++) {
			var p = pages[i];
			var item = self.resultItemModel.clone(false, false);
			var a = item.children('a').attr({ 'href': p.url });
			a.append('<span><b></b>' + p.pageName + '</span>').attr({ 'href': p.url, 'data-name': p.pageName }); ;

			var image = p.getImage('Image', Cossette.CMS.ImageSize.SMALL);
			if (image != '')
				a.find('.image').attr({ 'src': image });
			else
				a.find('.image').remove();

			temp.append(item);
			
			K7.GA.event('suggest', 'invite', p.pageName);
		}

		// affiche les résultats
		self.results.append(temp.html()).show();

		// bind events
		self.results.find('a').bind('click', function() {
			var t = $(this);
			K7.GA.event('suggest', 'click', t.data('name'));
			setTimeout("window.location = '"+t.attr('href')+"';", 200);
			return false;
		});
		

		self.itemHeight = self.results.find('.item:first-child').height();

		if (pages.length > 3)
			self.nextButton.removeClass('disabled');

		self.resultsWrapper.css({ 'height': (self.itemHeight * (pages.length > 3 ? 3 : pages.length)) + 'px' });
		self.resultsWrapper.show();
		self.noresults.hide();

		delete temp;
	}
};

Claritin.Widget.ClaritinSuggests.prototype.gatherFindOptions = function() {
	var self = this;
	var findOptions = $.extend({}, self.FindOptions);

	findOptions.symptoms = [];
	findOptions.age = $('#suggestsAge').val();
	findOptions.relief = $('#suggestsRelief').val();

	var symptomsCB = $('input[type=checkbox].symptom');
	for (var i = 0, l = symptomsCB.length; i < l; i++) {
		var s = symptomsCB.eq(i);
		if (s.is(':checked'))
			findOptions.symptoms.push(s.val());
	}
	return findOptions;
};

Claritin.Widget.ClaritinSuggests.prototype.find = function(findOptions, callback) {
	var self = this;
	var f = findOptions;
	if (f.age == '')
		return;
	if (f.relief == '')
		return;
	var symptomsReq = '';
	for (var i = 0, l = f.symptoms.length; i < l; i++)
		symptomsReq += "'Symptom" + f.symptoms[i] + "'" + (i < f.symptoms.length - 1 ? "," : "");
	var q = "Age = '" + f.age + "' AND (Relief = '" + f.relief + "' OR Relief IS NULL) AND (SymptomRequired IS NULL OR SymptomRequired IN (" + symptomsReq + "))";
	for (var i = 0, l = f.symptoms.length; i < l; i++)
		q += " AND Symptom" + f.symptoms[i] + " = '1'";
	Cossette.CMS.CMServices.pagesByModel(
		{ 'modelCode': 'Product', 'query': q },
		function(pages/*, startRowIndex, maximumRows, totalCount*/) {
			self.renderResults(pages);
			if (typeof callback == 'function')
				callback(pages);
		}
	);
};
