'use strict'; // Enable ECMAScript 'strict' operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
/*jslint onevar: true, browser: true, forin: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, maxerr: 300 */
/*global window: false, jQuery: false, $: false, swfobject: false */

$(function(){
	var animationSelector = '#silkeandpatricia-animation',
		headerSelector = '#header',
		mottoSelector = '#motto',
		navSelector = '#main-navigation',
		sideNavSelector = '#side-navigation',
		sideSelector = '#side-content',
		contentSelector = '#main-content',
		last = { url: false, target: false },
		numEvents = 3;

	function resizeIframe() {
		$('iframe.autoHeight').bind('load', function(){
			var elem = $(this).get(0),
				newHeight = elem.contentDocument
					? elem.contentDocument.body.offsetHeight + 35
					: elem.contentWindow.document.body.scrollHeight;

			$(this).height(newHeight);
		});
	}

	function updateContent(htmlDOM) {
		$(contentSelector).replaceWith( $(contentSelector, htmlDOM) );

		resizeIframe();
	}

	function updateHeader(htmlDOM) {
		$(headerSelector).replaceWith( $(headerSelector, htmlDOM) );

		if(!$(animationSelector).find('object').length > 0) {
			setupAnimation();
		}
	}

	function updateMotto(htmlDOM) {
		$(mottoSelector).replaceWith( $(mottoSelector, htmlDOM) );
	}

	function updateNav(htmlDOM) {
		$(navSelector).replaceWith( $(navSelector, htmlDOM) );
		$(sideNavSelector).replaceWith( $(sideNavSelector, htmlDOM) );
	}

	function updateSide(htmlDOM) {
		$(sideSelector).replaceWith( $(sideSelector, htmlDOM) );
	}

	function setupAnimation() {
		var params = { wmode: 'transparent' },
			attributes = { id: animationSelector.substr(1) };

		swfobject.embedSWF('/assets/templates/silkeandpatricia/flash/silkeandpatricia-animation.swf', animationSelector.substr(1), '468', '468', '9.0.0', false, {}, params, attributes);
	}

	function navigationEvent(url) {
		function success(html) {
			var htmlDOM = $(html),
				bodyClass = html.match(/<body[^>]class='(.*)'/i),
				speed = 'slow',
				isStart = last.target.parents('.start, #logo').length > 0,
				isLang = last.target.parents('[class^=\'yam\']').length > 0,
				curLang = last.target.parent().siblings('.active').children('a').attr('lang'),
				newLang = last.target.attr('lang');

			// Remove previous animation and update navigation
			$(animationSelector + ' *', htmlDOM).empty().hide();
			updateNav(htmlDOM);

			// Check if language was selected
			if(isLang) {
				// Set cookie to keep track
				$.cookie('last_language', newLang);

				// Update content
				updateHeader(htmlDOM);
				updateContent(htmlDOM);
				updateSide(htmlDOM);

				// MAke all links absolute to prevent problems with language switcher
				$('a:not([href^="http://"]').attr('href', function(i, val) {
					return '/'+newLang+'/'+val;
				})
			}

			// Lanauge wasn't selected, animate header if needed
			else {
				// Toggle background id/class
				$(document.body)
					.attr('id', isStart ? 'start' : '')
					.attr('class', bodyClass && bodyClass[1] ? bodyClass[1] : '');

				// Start page was requested
				if(isStart) {
					(!$(animationSelector).length && updateHeader(htmlDOM));
					$(headerSelector).height(150);
				}
				// Start page wasn't requested, hide animation before sliding header
				else if(!isLang){
					$('#animation').hide();
				}

				// Animate header
				$(headerSelector).animate({
					height: isStart ? 478 : 150
				},
				speed, 'swing', function (){
					// Update content
					updateContent(htmlDOM);
					updateSide(htmlDOM);

					// Setup animation if needed and show it
					if(isStart) {
						$('#animation').show();
					}
				});

				// Scroll back to the top of the page when animating header
				($(headerSelector+':animated') && $(window).scrollTop() > 400 && $(window).scrollTop(0));
			}
		}

		// Use current path name if no URL is provided
		if(last.url && !url){
			url = document.location.pathname;
			last.target = $('<div/>');
		}

		// Retrieve content via AJAX if needed
		if(url && last.url !== url) {
			$.ajax({ url: url, success: success });
		}

		// Cache URL
		last.url = url;
	}

	//  Setup more events button
	/*
	$('.events-more a').live('click', function(){
		$.ajax({
			url: $(this).attr('href'),
			context: $(this).parent(),
			dataFilter: function(html){
				return $(html).find('.vevent');
			},
			success: function(events){
				$(this).before(
					events.filter(':gt('+($('.vevent', $(sideSelector)).length + 1)+'):lt('+numEvents+')')
				);
			}
		});
	});
	*/

	//open all external links in new window
	
	/*
	$('a').not('[href^="http://www.silkeandpatricia.com/"], [href^="http://silkeandpatricia.com/"]')
		.click(function(){
			window.open( $(this) .attr('href') );
			return false;
		})
		.attr('title', 'Opens in a new window');
	*/
		
	/*	
		$("a:not([href*='silkeandpatricia.com'])").click(function(){
			window.open(this.href);
			return false;
		}).attr("title", "Opens in a new window");	
	
	*/
	/*	
		$("a:not([@href*=http://silkeandpatricia.com/])").not("[href^=#]")
		        .addClass("external")
		        .attr({ target: "_blank" });
		  
		
	
	$('a[href^="http://"]')
	  .attr({
	    target: "_blank", 
	    title: "Opens in a new window"
	  });
	*/

	// Setup animation and iframe
	setupAnimation();
	resizeIframe();


	/* =========================================================================== */
	/* ========== COMMENT THIS PART OUT TO DISABLE AJAX PAGE LOADING ============= */
	/* =========================================================================== */

/*

	// Setup history tracker and navigation urls
	$.history.init(navigationEvent);
	$('a[href^='+location.href.replace(location.pathname,'')+'], a[href=/]').live('click', function(event){
		// Check its not a manager url or the more events button
		//if((/\/manager.$/i).test($(this).attr('href')) || $(this).parent('.events-more').length > 0){

		if((/\/manager.$/i).test($(this).attr('href'))){
			return false;
		}

		// Cache the event
		last.target = $(this);

		// Setup and format URL
		var url = $(this).attr('href') + '';
		url = url.replace(/^.*#/, '').replace('http://'+document.location.hostname, '');

		// Load the new page and put into browser history
		$.history.load(url);

		return false;
	});

*/

	/* =========================================================================== */
	/* =============================== END COMMENT  ============================== */
	/* =========================================================================== */
});



jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
