/*jslint bitwise: true, eqeqeq: true, passfail: false, nomen: true, plusplus: false, undef: true, evil: true */
/*global LBI, sIFR, named, window, document, $, jQuery */

/**
 * Perfunkt Core
 * @namespace Perfunkt functionality.
 * @see /assets/readme.txt
 * @version 1.0
 * @author LBi - http://www.lbi.com/en
 * @requires LBI.common
 * @requires jQuery Core 1.4.4 - http://www.jquery.com/
 * @requires jQuery Cookie Plugin
 * @requires jQuery Colorbox Plugin
 * @requires jQuery Perfunkt Plugins
*/


var PF = {

    /**
     * Main entry point.
     */
    init: function () {
	
		LBI.common.dynamicInputText();
		LBI.common.getNewWindowLinks();
		LBI.common.frameKill();
		
		PF.sifr.init();
		PF.ajax.init();
		PF.overlays.init();
		PF.toggled.init();
		PF.tabs.init();
		PF.printLink();
		
		$("textarea.charcount").charCount();
		$("#shared input.remove,#liked input.remove").confirmDialog();
		
		if ($( '.carousel' ).length > 0) {
			window.carousel = new PCarousel( $( '.carousel' ) );
		}
    },
	
	printLink: function() {
		
		$( '.print-link' ).bind( 'click', function( evt ) {
			evt.preventDefault();
			window.print();
		});
		
	},
	
    /**
     * @namespace sIFR 
     */
	sifr: {

		/**
		 * Default replacement settings
		 */
		defaultSettings: {
			sSelector:"", 
			sFlashSrc:"/assets/SIFR/whitneybold.swf", 
			sColor:"#000000",
			sWmode: "transparent"
		},

		/**
		 * Replacement settings
		 */
		settings: [
			// { sSelector: ".sectionHeading>em" },
			{ sSelector: ".sectionHeading>span", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".ideas h2 em" },
			{ sSelector: ".ideas h2 span", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".intro h1.itemTitle", sColor:"#FFFFFF", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".profile h1.itemTitle", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: "h1.videoTitle", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: "h1.tagHeading" },
			{ sSelector: "#greeting", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: "#usercontent h2#become em", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			
			{ sSelector: ".sectionHeading em", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".expertInfo h3 span", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".expertInfo h3 em", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".header-special span", sColor:"#FF5025", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".header-special em", sColor:"#252525", sCase: 'upper', sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".event-name h2", sColor:"#FFFFFF", sCase: 'upper', sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".event-location-primary", sFlashSrc:"/assets/SIFR/whitneybook.swf", sFlashVars: 'textalign=right' },
			{ sSelector: ".booking h1", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".bookingBreadcrumbs li.active", sColor:"#FFFFFF", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".bookingBreadcrumbs li", sColor:"#a8a4a4", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".bookingName h2", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".booking .sectionHeading", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybold.swf" },
			{ sSelector: ".booking p.price span", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".booking p.price em", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".booking .bookText", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".booking .bookTextPlaces", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".bookingLocation p .place", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".bookingLocation p .city em, .bookingLocation p .country em", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".bookingDate .formField em", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".bookingDate .formField .time", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".bookingPanel .bookingName em", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".bookingPanel .summary-2 p span.price", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".bookingPanel em.semiBold", sColor: "#6e6767", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".form .booking-section>p", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".form .booking-section .cta p em", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".form .booking-section .cta p span", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".booking .form h3", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".booking .form label", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".booking .form p.info, .booking .form p.info2", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".form .booking-section .commentform h4", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".masterclass-content h1", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: "h2.special", sColor: "#FF5025", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".carousel-subcontent h3 span", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".carousel-subcontent h3 em", sColor: "#252525", sCase: 'upper', sFlashSrc:"/assets/SIFR/whitneybold.swf" },
			{ sSelector: ".masterclass-lessoninfo h3 em", sColor: "#252525", sCase: 'upper', sFlashSrc: '/assets/SIFR/whitneybold.swf' },
			{ sSelector: ".masterclass-lessoninfo h3 span, .masterclass-lessoninfo p span", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			// { sSelector: ".masterclass-lessoninfo p em", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".masterclass-ticketinfo h3 span", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".masterclass-ticketinfo h3 em", sColor: "#FF5025", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".masterclass-ticketinfo p", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".event-rightblock .event-time, .event-location-secondary", sFlashSrc:"/assets/SIFR/whitneysemibold.swf", sFlashVars: 'textalign=right' },
			{ sSelector: ".event-day, .event-month", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".event-time", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".newsletter h2, .share h2", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			// { sSelector: ".newsletter .intro", sColor: "#808285", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".archive-module h3 span", sFlashSrc:"/assets/SIFR/whitneybook.swf" },
			{ sSelector: ".archive-module h3 em", sCase: 'upper', sFlashSrc:"/assets/SIFR/whitneysemibold.swf" },
			{ sSelector: ".archive-module h4", sColor: "#252525", sFlashSrc:"/assets/SIFR/whitneysemibold.swf" }
		],

		/**
		 * Initialise sIFR
		 */
		init: function() {
			if(typeof sIFR === "function") {
				for(var i = 0; i < PF.sifr.settings.length; i++) {
					var options = $.extend({ }, PF.sifr.defaultSettings, PF.sifr.settings[i]);
					var elements = $( options.sSelector );
					options['nPaddingTop'] = parseInt( elements.css( 'padding-top' ), 10 );
					options['nPaddingRight'] = parseInt( elements.css( 'padding-right' ), 10 );
					options['nPaddingBottom'] = parseInt( elements.css( 'padding-bottom' ), 10 );
					options['nPaddingLeft'] = parseInt( elements.css( 'padding-left' ), 10 );
					
					sIFR.replaceElement(named(options));
				}
			}
		}		
	},

    /**
     * @namespace Ajax functionality.
     */
	ajax: {

		/**
		 * Reusable POST Request
		 *
		 * @param {Object} DOM Element (form input)
		 * @param {Function} Callback
		 */
		post: function(element, callback) {
			var form = $('form:first'),
				formaction = form.attr('action'),
				url = LBI.common.ajax.tagUrl(formaction),
				// adding values for submit button manually
				submitvalue = "&" + encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value).replace(/%20/g, '+'),
				params = form.serialize() + submitvalue;
				
			$.post(url, params, function(data) { 
				callback.call(element, data); 
				window.setTimeout($.colorbox.resize, 100);
				LBI.common.ajax.pageUpdated();				
			});			
		},

		/**
		 * Initialise Account-related Ajax functionality
		 */
		initAccount: function() {
			// sign-in
			$('#signinSubmit input').live("click", function () {
				PF.ajax.post(this, function(data) { 
					$("#signin").html(data); 
				});
				return false;
			});
			
			// join
			$('#joinSubmit input:submit').live('click', function() {
				PF.ajax.post(this, function(data) { 
					$("#join").html(data);
				});
				return false;				  
			});
			
			// forgot password
			$('#forgotSubmit input:submit').live('click', function() {
				PF.ajax.post(this, function(data) { 
					$("#forgot").html(data);
				});
				return false;				  
			});				
		},

		/**
		 * Initialise video tools related Ajax functionality
		 */
		initVideotools: function() {
			// share
			$('#shareSubmit input').live('click', function() {
				PF.ajax.post(this, function(data) { 
					$("#share").html(data);
				});
				return false;				  
			});
	
			// like buttons
			$('#videocomments .like').click(function () {
				PF.ajax.post(this, function(data) { 
					$(this).parent().replaceWith(data);
					var likeCount = $('.videoInfo .likes');
					var likeCountNo = likeCount.find('.number');
					var currentCount = parseInt(likeCountNo.text());
					if (currentCount == 0) {
					    likeCount.addClass('singlelike');
					} else {
					    likeCount.removeClass('singlelike');
					}
					currentCount += 1;
					likeCountNo.text(currentCount);
				});
				return false;
			});
	
			// flag as inappropriate
			$('#videocomments .inappropriate,.commentsContainer .inappropriate').click(function () {
				PF.ajax.post(this, function(data) { 
					$(this).replaceWith(data);
				});
				return false;
			});			
		},

		/**
		 * Initialise Ajax handlers
		 */
		init: function() {
			PF.ajax.initAccount();
			PF.ajax.initVideotools();
		}
	},

    /**
     * @namespace Overlay functionality.
     */
    overlays: {
		
		/**
		 * Default overlay settings 
		 */
		defaultSettings: {
			selector: "",
            inline: true,
            loop: false,
            arrowKey: false,
            opacity: 0.8,
            initialWidth: "342"
        },
		
		/**
		 * Settings for individual overlays
		 */		
		 settings: [
			// about
			{ selector: "#header .dialogAbout,#aboutstars a,p.mainIntro a.actionlink",  href: "#about", initialWidth: "500" },	
			// share with a friend
			{ selector: "#videocomments .sendToFriend",  href: "#share" },
			// header overlays
			{ selector: "#header .dialogJoin",  href: "#join", rel: "dialogs", initialWidth: "500" },
			{ selector: "#header .dialogSignin",  href: "#signin", rel: "dialogs" },
			{ selector: "#forgotpass",  href: "#forgot", rel: "dialogs" },
			// sidebar overlays
			{ selector: "#joinContainer .dialogJoin",  href: "#join", rel: "dialogsSidebar", initialWidth: "500" },
			{ selector: "#joinContainer .dialogSignin",  href: "#signin", rel: "dialogsSidebar" },
			{ selector: "#forgotpassJoin",  href: "#forgot", rel: "dialogsSidebar" },
			{ selector: "#sidebar .share .sendToFriend",  href: "#share" }
		],

		/**
		 * Create overlays
		 */	
        initMain: function () {
			for(var i = 0; i < PF.overlays.settings.length; i++) {
				var options = $.extend({}, PF.overlays.defaultSettings, PF.overlays.settings[i]);
				$(options.selector).colorbox(options);
			}
        },

		/**
		 * <p>Initialise close buttons & links</p>
		 * <p>Note: 'previous' & 'next' links are used to switch between different overlays</p>
		 */
        initLinks: function () {

            $('#colorbox .next').live('click', function () {
                $.colorbox.next();
                return false;
            });
            $('#colorbox .prev').live('click', function () {
                $.colorbox.prev();
                return false;
            });
            $('#colorbox .close').live('click', function () {
                $.colorbox.close();
                return false;
            });

        },

		/**
		 * Initialise overlays
		 */
        init: function () {
            PF.overlays.initMain();
            PF.overlays.initLinks();

        }

    },

    /**
     * @namespace Tabs
     */
	tabs: {
		/**
		 * Initialising tabs
		 */		
		init: function() {
			
			// handlers for user sidebar
			$('#usernav a').simpleTabs({ tabpanels: '#userpanel .contentPane' });
			// opening add item pane from the initial pane
			$('#addContribution').click(function() {
				$('#userAdd').click();
				return false;
			});

			// handlers for profile container
			$('#profilenav a').simpleTabs({ tabpanels: '.profilePane' });
			
		}
	},

    /**
     * @namespace Toggled panels
     */
	toggled: {

		/**
		 * Initialising toggled panels
		 */
		init: function() {
			PF.toggled.initBasic();
			PF.toggled.initActivity();
		},

		/**
		 * Initialising basic panels
		 */
		initBasic: function() {
			// language selector
			$('#header .languageSelector').hover(function () {
				$(this).find("li").not(".active").addClass("show");
			}, function () {
				$(this).find("li").not(".active").removeClass("show");
			});
	
			// profile image upload form
			$('#pictureupload').click(function () {
				$('#uploadform').fadeToggle();
				return false;
			});
	
			$("#main .more").click(function() {
				$(this.hash).fadeToggle();
				return false;
			});
	
			// FAQs
			var faqQuestions = $('#faq dt');
			var faqAnswers = $('#faq dd');
			faqQuestions.click(function () {
				faqQuestions.removeClass("active");
				faqAnswers.removeClass("active");
				$(this).addClass("active").next().addClass("active");
			});			
		},
		
		/**
		 * recent activity panel
		 */
		initActivity: function() {
			var heading = $('#account .activityHeading');
			if($.cookie('sidebaropen') === '0') {
				heading.removeClass("active");
				var id = heading.find('a:first');
				var link = heading.find('a:first');
				if(link.length) {
					var hash = link.get(0).hash;
					$(hash).fadeOut();
				}
			} else {
				heading.addClass("active");
				$.cookie('sidebaropen', '1', { path: '/' });
			}
			$('#account .activityHeading a').click(function() {
				var heading = $(this).parent(),
					open = heading.is(".active");
				if(open) {
					$(this.hash).fadeOut();
					heading.removeClass("active");
					$.cookie('sidebaropen', '0', { path: '/' });
				} else {
					$(this.hash).fadeIn();
					heading.addClass("active");	
					$.cookie('sidebaropen', '1', { path: '/' });
				}
				return false;			
			});			
		}

	}
	
};
	
function PCarousel() {
	
	this.init.apply( this, arguments );
	
}

PCarousel.prototype.init = function( node, options ) {
	
	this.reset( node, options );
	
}

PCarousel.prototype.add = function( control, content, batch ) {
	
	var item = { control: control, content: content };
	this.items[this.items.length] = item;
	
	var me = this;
	$( control ).bind( 'click', function( evt ) {
		evt.preventDefault();
		me.select( item );
	} );
	
	if ($( item.control ).hasClass( 'active' )) {
		this.select( item );
	}
	
	if (!batch) {
		this.configure();
	}
	
}

PCarousel.prototype.batch = function( controls, containers ) {
	
	for (var i = 0, j = containers.length; i < j; i++) {
		this.add( controls[i], containers[i], true );
	}
	
	if (!this.selected && this.items.length > 0) {
		this.select( this.items[0] );
	}
	
	this.configure();
	
}

PCarousel.prototype.configure = function() {
	
	this.slide_distance = $( this.items[0].control ).width() + 5;
	this.slide_width = (this.slide_distance * this.items.length) - 5;
	
	this.slide_viewport = $( this.node ).find( '.carousel-control-container' ).width();
	this.slide_variance = this.slide_width - this.slide_viewport;
	
}

PCarousel.prototype.reset = function( node, options ) {
	
	this.node = node;
	this.options = options || undefined;
	
	this.content = $( this.node ).find( '.carousel-content' );
	this.control = $( this.node ).find( '.carousel-control' );
	this.thumbnail = $( this.node ).find( '.carousel-thumbs' );
	
	var containers = $( this.content ).find( 'li' );
	var controls = $( this.control ).find( 'li a' );
	
	if (containers.length < 2) {
		return false;
	}
	
	$( this.node ).addClass('carouselEnable');
	
	this.items = [ ];
	this.batch( controls, containers );
	
	var me = this;
	$( this.node ).find( '.carousel-previous' ).bind('click', function( evt ) {
		evt.preventDefault();
		me.slide( -1 );
	});
	$( this.node ).find( '.carousel-next' ).bind('click', function( evt ) {
		evt.preventDefault();
		me.slide( 1 );
	});
	
}

PCarousel.prototype.select = function( item ) {
	
	if (this.selected !== undefined) {
		$( this.selected.control ).removeClass( 'active' );
		$( this.selected.content ).removeClass( 'active' );
	}
	
	$( item.control ).addClass( 'active' );
	$( item.content ).addClass( 'active' );
	
	this.selected = item;
	
}

PCarousel.prototype.slide = function( move ) {
	
	var offset = $( this.thumbnail )[0].offsetLeft;
	if (this.animation_destination !== undefined) {
		offset = this.animation_destination;
	}
	
	var destination = offset - (move * this.slide_distance);
	if (Math.abs( destination ) <= this.slide_variance && destination <= 0) {
		this.animation_destination = destination;
		
		var me = this;
		$( this.thumbnail ).animate( { 'left' : destination + 'px' }, { 'callback' : function() {
			me.animation_destination = undefined;
		} });
	}
	
}

/*
 * Initialise Perfunkt Core
 */
$(document).ready(PF.init);
