
var stejar = function () {
    var self = this;
    this._loadFacebook = function () {
        try {
            iFACScripts.init();
        } catch (err) {}
        try {
            FB.XFBML.Host.parseDomTree();
        } catch (err) {}
        // try { _gaq.push(['_trackPageview']); } catch(err) {}
    }
    this._ageValidation = function () {

        var dayIsValid = function () {
            var day = $('#dayAge').val();
            //alert(day);
            if (isNaN(day) || !day || day < 1 || day > 31 || day.length > 2) {
                return false;
            }
            return true;
        }

        var monthIsValid = function () {
            var month = $('#monthAge').val();
            if (isNaN(month) || !month || month < 1 || month > 12 || month.length > 2) {
                return false;
            }
            return true;
        }

        var yearIsValid = function () {
            var year = $('#yearAge').val();
            if (isNaN(year) || !year || year < 1910 || year > 2010 || year.length > 4) {
                return false;
            } 
            return true;
        }
        //splash page
        var returns = false;
        var age_is_valid = true;
        $('#yearAge').val('AAAA');
        $('#monthAge').val('LL');
        $('#dayAge').val('ZZ');
        $('#ageCheckForm #dayAge').focus().val('');
        $('#ageCheckForm #monthAge').focus(function () {
            if (returns) {
                $('#datesubmit').val('introdu luna corect').addClass('error');
            }
            if (!dayIsValid()) {
                age_is_valid = false;
                $('#datesubmit').val('introdu ziua corect').addClass('error');
                $('#dayAge').val('').focus();
                returns = true;
            }

        });
        $('#ageCheckForm #yearAge').focus(function () {
            if (returns) {
                $('#datesubmit').val('introdu anul corect').addClass('error');
            }
            if (!monthIsValid()) {
                age_is_valid = false;
                $('#datesubmit').val('introdu luna corect').addClass('error');
                $('#monthAge').val('').focus();
                returns = true;
            }
        });
        $('#ageCheckForm #datesubmit').focus(function () {
            if (returns) {
                //$('#datesubmit').val('introdu anul corect').addClass('error');
            }
            if (!yearIsValid()) {
                age_is_valid = false;
                $('#datesubmit').val('introdu anul corect').addClass('error');
                $('#yearAge').val('').focus();
                returns = true;
            } else {
                age_is_valid = true;
                returns = false;
				$('#datesubmit').val('continua');
            }

        });

        $('#ageCheckForm').submit(function () {
            
			var year = parseInt($('#yearAge').val());
            var month = parseInt($('#monthAge').val()) - 1;
            var day = parseInt($('#dayAge').val());
            var date = new Date(year, month, day);
            var old_date = new Date(1992, month, day);
            var max_date = new Date(1910, month, day);			
			
			
			
			if (date < old_date && date >= max_date) {
                age_is_valid = true;
            } else {
				age_is_valid = false;
			}
			
            if (age_is_valid) {
                $('#age').hide();
                $('body').removeClass("inactive");
				self._loadTheme();
                var date = new Date();
                date.setTime(date.getTime() + 3600 * 1000);
                $.cookie('age', 'yes', {
                    path: '/',
                    expires: date
                });
            } else {
                if (!dayIsValid()) {
                    age_is_valid = false;
                    $('#datesubmit').val('introdu ziua corect').addClass('error');
                    $('#dayAge').val('').focus();
                    $('#yearAge').val('AAAA');
                    $('#monthAge').val('LL');
                } else {
                    if (!monthIsValid()) {
                        age_is_valid = false;
                        $('#datesubmit').val('introdu luna corect').addClass('error');
                        $('#monthAge').val('').focus();
                        $('#yearAge').val('AAAA');
                    } else {
                        if (!yearIsValid()) {
                            age_is_valid = false;
                            $('#datesubmit').val('introdu anul corect').addClass('error');
                            $('#yearAge').val('').focus();
                        } else {
                            $('#datesubmit').val('trebuie sa ai 18+ ani').addClass('error');
                            $('#ageCheckForm #dayAge').val('').focus();
                            $('#yearAge').val('AAAA');
                            $('#monthAge').val('LL');
                        }
                    }
                }
            }			
            return false;
        });

    };

    this._loadHash = function (hash) {
		//parse hash and load stuff
        var qsPices = hash.split('?');
        query = qsPices[1] || null;
        var pieces = qsPices[0].replace('#', '').split('&');
        $.each(pieces, function (item, value) {
            var type = pieces[item].split('=');
			var value = type[1];
            switch (type[0]) {
            case 'page':
				self._loadPage(value, query);
                break;            
            case 'section':				              
			self._loadSection($('#' + value));
                break;
            }
        });
    }
    this._setHash = function (item) {
        var v = item.split('=');
        var property = v[0];
        var value = v[1];		
        var hash = document.location.hash.substring(1, document.location.hash.length);
        if (hash.indexOf(property) != -1) {

            var aux = (hash.indexOf('&') == -1) ? [hash] : hash.split('&');
            var hash_v = {};
            var last = '';
            $.each(aux, function (item, value) {
                var aux_b = [];
                aux_b = value.split('=');
                hash_v[aux_b[0]] = aux_b[1];
                last = aux_b[0];
            });
            old_value = hash_v[property];
            hash_v[property] = value;
            var new_hash = '';
            $.each(hash_v, function (item, value) {
                var x = ((value == undefined) ? '' : value).toString().replace('#', '%23');
                new_hash += (item == last ? item + '=' + x : item + '=' + x + '&');
            });
            document.location.hash = new_hash;
        } else {
            document.location.hash += (document.location.hash.length > 2 ? '&' : '') + property + '=' + value.replace('#', '%23');
        }

        var has_no_query = document.location.hash.lastIndexOf('?') == -1 ? true : false;
        if (query && has_no_query) {
            document.location.hash += '?' + query;
        } else {
            if (query && !has_no_query) {
                document.location.hash += '=' + query.split("=")[1];
            }
        }

    }
    this._removeHash = function (param) {
        var hash = document.location.hash.replace('#', '');
        if (hash.indexOf(param) != -1) {
            var old_value = hash.substring(hash.indexOf('=', hash.indexOf(param)) + 1, (hash.indexOf('&', hash.indexOf(param)) != -1 ? hash.indexOf('&', hash.indexOf(param)) : hash.length));
            var has_amp = hash[hash.indexOf(old_value) + 1] == '&' ? true : false;
            var to_replace = (hash[hash.indexOf(param) - 1] == '&' ? '&' : '') + param + '=' + old_value + (has_amp ? '&' : '');
            hash = hash.replace(to_replace + '&', '').replace('&' + to_replace, '').replace(to_replace, '');
            document.location.hash = hash;
        }

    }

    this._loadPage = function (href, data) {

		$('#map div.box').each(function(i, el) {			
			self._closeSection(el);			
		});
        var selector = '#blogPage';
        var protocol = document.location.protocol;
        var host = document.location.host;
        var pathname = href.replace(protocol + '//' + host, '');
        self._setHash('page=' + pathname, data);
        self._removeHash('section');

		//analytics track		
		var link = location.hash.replace('#page=','');			  
		//  _gaq.push(['_trackPageview', link]);	
		try { _gaq.push(['_trackPageview', link]); } catch(err) {}	


        $('#fancybox').fadeIn();
        $('#fancybox-content').html('<div id="blogPage"><div class="blogPagePrimary"><h1 class="loading">se încarcă...</h1></div></div>');
        //$.scrollTo('150px', 500);
        //href = decodeURIComponent(href.toString().replace('%23','#'));
        href = href.substring(0, href.lastIndexOf('/') + 1);
        jQuery.ajax({
            url: href,
            data: data || null,
            dataType: "html",
            complete: function (res, status) {
                // If successful, inject the HTML into all the matched elements
                //alert('done ' + href + ' status ' + status + res.responseText);
                if (status === "success" || status === "notmodified") {
                    $('#fancybox-content').html(selector ?
                    // Create a dummy div to hold the results
                    jQuery("<div />")
                    // inject the contents of the document in, removing the scripts
                    // to avoid any 'Permission Denied' errors in IE
                    .append(res.responseText)
                    //.replace(/<script(.|\s)*?\/script>/gi, ""))
                    // Locate the specified elements
                    .find(selector) :

                    // If not, just inject the full result
                    res.responseText);
                    self._loadFacebook();
                    $('#fancybox-content').find('.blogPageTitle a, .blogPageBody a, .blogPageSecondary a, .blogPageContent div.posts a').bind('click', function (e) {
                        var rel = $(this).attr('rel');
						var target =  $(this).attr('target');
                        if (target != '_blank') {
                            var query = this.href.lastIndexOf('?') != -1 ? this.href.substring(this.href.lastIndexOf('?') + 1, this.href.length) : null;
                            self._loadPage(this.href, query);
                            return false;
                        }
                    });
                    $('#fancy-close').click(function () {
                        self._closePage();
                        return false;
                    });					
						
					self._changeMovie();
                } 
            }
        });
    }

    this._closePage = function () {
        $('#fancybox').fadeOut();
        $('#fancybox-content').empty();
        self._removeHash('page');
    }

    this._closeSection = function (section) {            
		$('.sectionContent',section).fadeOut();
		$(section).removeClass('open');
		$('div.boxContent ul.items', section).removeClass('open');
		self._removeHash('section');        
    }

    this._loadSection = function (section) {

		var is_opened_section = $('div.box.open').size() ? true :false;
		self._closeSection($('div.box.open'));
		$(section).addClass('open');
		$('div.boxContent ul.items', section).addClass('open');		
		self._setHash('section=' +  $(section).attr('id'));
		var container = $('.sectionContent',section);
        var selector = 'div.blogPageContent';
		var href = $('div.boxPresentation h2 a', section).attr('href');
        var protocol = document.location.protocol;
        var host = document.location.host;		
        var pathname = href.replace(protocol + '//' + host, '');

		
		var isEmpty = $(container).is(":empty") ? true : false;		
		container.show();
		if (isEmpty) { 
			container.html('<p class="loading">se încarcă...</p>'); 
			href = href.substring(0, href.lastIndexOf('/') + 1);				
			jQuery.ajax({
				url: href,            
				dataType: "html",
				complete: function (res, status) {
					// If successful, inject the HTML into all the matched elements
					//alert('done ' + href + ' status ' + status + res.responseText);
					if (status === "success" || status === "notmodified") {
						container.html(selector ?
						// Create a dummy div to hold the results
						jQuery("<div />")
						// inject the contents of the document in, removing the scripts
						// to avoid any 'Permission Denied' errors in IE
						.append(res.responseText)
						//.replace(/<script(.|\s)*?\/script>/gi, ""))
						// Locate the specified elements
						.find(selector) :

						// If not, just inject the full result
						res.responseText);				

						
						$('div.post', container).bind('click', function (e) {														
							var href = $(this).find('h2 a').attr('href');
							var rel = $(this).find('h2 a').attr('rel');
							if (rel.indexOf('external') == -1) {
								var query = href.lastIndexOf('?') != -1 ? href.substring(href.lastIndexOf('?') + 1, href.length) : null;
								self._loadPage(href, query);
								return false;
							} else {
								href.attr('target', '_blank');
							}
						});

						$('div.boxPresentation h2 a', section).click(function(){
							var url = $(this).attr('href');							
							if (section.hasClass('open')) {
								self._loadPage(url);
							} else {
								self._loadSection(section);
							}
							return false;
						});

						$(section).unbind('click').click(function(e){							
							if (!$(container).is(':visible')) {
								self._loadSection(section);			
							} 
							e.stopPropagation();							
						});

						var control_markup = '<div class="controls"><a href="#" class="close">close</a><a href="#" class="explore">explore</a></div>';
						$(container).before(control_markup);
						var v_height = $('div.posts', container).height();
						var height = $(container).height();
						if (v_height > height) {
							$('div.controls', section).show();
							var prevnext_markup = '<a href="#" class="prev">prev</a><a href="#" class="next">next</a>';
							$('.controls',section).prepend(prevnext_markup);
						
							$('div.controls a.prev', section).unbind('click').live('click',function(){		
								container.scrollTo('-=160px',300, {axis:'y', easing:'linear'});								
								return false;
							});
							$('div.controls a.next', section).unbind('click').live('click',function(){																
								container.scrollTo('+=160px',300, {axis:'y', easing:'linear'});
								return false;
							});
						}

						$('div.controls a.close', section).unbind('click').live('click',function(){								
							$(section).removeClass('open');
							$(container).hide();
							self._removeHash('section');
							return false;
						});
						$('div.controls a.explore', section).unbind('click').live('click',function(){								
							var url = $('div.boxPresentation h2 a',section).attr('href');							
							self._loadPage(url);
							
							return false;
						});
					} 
				}
			});
		}
		
        
    }

	this._changeMovie = function(){
		var flv = [
			{
			url: 'rugby.flv',
			text: 'Dacă aşa te relaxezi după o zi de muncă, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
			image: 'rugby-bg.jpg'
			
			},
			{
				url: 'hublou.flv',
				text: 'Dacă acesta e primul lucru pe care îl vezi pe fereastră dimineața, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'
				
			},
			{
				url: 'sudor.flv',
				text: 'Dacă aceştia sunt ochelarii tăi preferaţi de soare, noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'welder-bg.jpg'
			},
			{
				url: 'hublou.flv',
				text: 'Dacă acesta e primul lucru pe care îl vezi pe fereastră dimineața, noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'
				
			},
			{
				url: 'hublou.flv',
				text: 'Dacă acesta e primul lucru pe care îl vezi pe fereastră dimineața, noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'
				
			},
			{
				url: 'sudor.flv',
				text: 'Daca nu iti este frica de ceea ce vezi, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'welder-bg.jpg'
			},
			{
				url: 'hublou.flv',
				text: 'Daca te poti uita lejer la aceasta pagina, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'

			}
		]

		var count = flv.length; 
		var win = Math.floor(Math.random() * (count - 1));	
		$('#header #logo #slogan').html(flv[win]['text']);
		$('#v_stejar').css('background','url("/wp-content/themes/stejar/static/images/' + flv[win]['image'] + '") center center no-repeat');

		if (jQuery.browser.flash){
			var timer = setInterval(function(){
					try {	
						
						var moviePlayer = moviePlayer || {};		 
						moviePlayer.instance = document.getElementById('player');
						moviePlayer.instance.changeMovie(flv[win]['url']);
						if ($('.controls .fl-sound').hasClass('inactive')) {
							moviePlayer.instance.mute(true);
							moviePlayer.isMute = true;
						}
						clearInterval(timer);
					} catch(err) {
					}
			}, 500);
		}
	}

	this._loadMovie = function(){
		var flv = [
			{
			url: 'rugby.flv',
			text: 'Dacă aşa te relaxezi după o zi de muncă, atunci avem ceva pentru tine',
			image: 'rugby-bg.jpg'
			
			},
			{
				url: 'hublou.flv',
				text: 'Dacă acesta e primul lucru pe care îl vezi pe fereastră dimineața, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'
				
			},
			{
				url: 'sudor.flv',
				text: 'Dacă aceştia sunt ochelarii tăi preferaţi de soare, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'welder-bg.jpg'
			},
			{
				url: 'hublou.flv',
				text: 'Dacă acesta e primul lucru pe care îl vezi pe fereastră dimineața, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'
				
			},
			{
				url: 'hublou.flv',
				text: 'Dacă acesta e primul lucru pe care îl vezi pe fereastră dimineața, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'
				
			},
			{
				url: 'sudor.flv',
				text: 'Daca nu iti este frica de ceea ce vezi, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'welder-bg.jpg'
			},
			{
				url: 'hublou.flv',
				text: 'Daca te poti uita lejer la aceasta pagina, atunci noul <strong>Stejar Strong</strong> ți se potrivește',
				image: 'boat-bg.jpg'

				}
		]

		var count = flv.length; 
		var win = Math.floor(Math.random() * (count - 1));	
		$('#header #logo #slogan').html(flv[win]['text']);
		$('#v_stejar').css('background','url("/wp-content/themes/stejar/static/images/' + flv[win]['image'] + '") center center no-repeat');
		
		if (jQuery.browser.flash){

			var params = {
				movie: "/wp-content/uploads/swf/player.swf", 
				wmode: 'transparent',
				allowScriptAccess: 'always',
				quality: 'high',
				allowFullScreen: 'true',
				flashvars: 'stream=' + flv[win]['url']
			}; 
			swfobject.embedSWF("/wp-content/uploads/swf/player.swf", "player", "100%", "100%",'9.0.0','','', params);
			
						
			var timer = setInterval(function(){
				try {
					var moviePlayer = moviePlayer || {};		 
					moviePlayer.instance = document.getElementById('player');
				
					moviePlayer.isMute = ($.cookie('sound') != null) ? ($.cookie('sound') == 'true' ? true : false ) : false;
					moviePlayer.isPlaying = ($.cookie('play') != null) ? ($.cookie('play') == 'true' ? true : false ) : true;	
					moviePlayer.instance.changeMovie(flv[win]['url']);
					if ($('.controls .fl-sound').hasClass('inactive')) {
						moviePlayer.instance.mute(true);
						moviePlayer.isMute = true;
					}

		
					if (moviePlayer.isPlaying) {
						moviePlayer.isPlaying = true;
						$('.controls .fl-play').html('stop').removeClass('inactive').addClass('active');
					} else {						
						$('#player').hide();
						moviePlayer.instance.stopMovie();
						moviePlayer.isPlaying = false;
						$('.controls .fl-play').html('play').removeClass('active').addClass('inactive');
					}
					
					if (moviePlayer.isMute) {
						moviePlayer.instance.mute(moviePlayer.isMute);						
						$('.controls .fl-sound').html('sound').removeClass('active').addClass('inactive');
						moviePlayer.isMute = true;
					} else {
						moviePlayer.instance.mute(moviePlayer.isMute);						
						$('.controls .fl-sound').html('mute').removeClass('inactive').addClass('active');
						moviePlayer.isMute = false;
					}	
					
					

					$('.controls a.fl-play').live('click',function(){						
						if (moviePlayer.isPlaying) {									
							$(this).html('play');	
							$('#player').hide();
							moviePlayer.instance.stopMovie();															
							moviePlayer.isPlaying = false;	
							$(this).html('play').removeClass('active').addClass('inactive');
			
						} else {
							$(this).html('stop').removeClass('inactive').addClass('active');
							self._changeMovie();	
							$('#player').show();							
							moviePlayer.isPlaying = true;
						}						
						$.cookie('play', moviePlayer.isPlaying);
						return false;
						
					});



					$('.controls a.fl-sound').click(function(){						
						if (moviePlayer.isMute) {							
							if ($('.controls .fl-play').hasClass('active')) {							
								moviePlayer.instance.mute(!moviePlayer.isMute);
								$(this).html('mut').removeClass('inactive').addClass('active');	
								moviePlayer.isMute = false;
							}
						} else {							
							if ($('.controls .fl-play').hasClass('active')) {							
								moviePlayer.instance.mute(!moviePlayer.isMute);
								$(this).html('sunet').removeClass('active').addClass('inactive');	
								moviePlayer.isMute = true;
							}		
						}
						$.cookie('sound',moviePlayer.isMute);
						return false;
					});

					clearInterval(timer);
				}
				catch(err) {
					//alert(err);
				}

			}, 500);
		}


	}

    this._loadTheme = function () {

		self._loadMovie();

        $('#widgets a').click(function () {
            var rel = $(this).attr('rel');
            var host = document.location.host;
            var url = $(this).attr("href");
            var is_blank = $(this).attr('target') == '_blank' ? true : false;
            var is_valid = $(this).attr("href").indexOf(host) != -1 ? true : false;
            if (!is_blank && is_valid) {
                self._loadPage(this.href);
                return false;
            } else {
                $(this).attr('target', '_blank');
            }
        });

        $("#map div.box div.boxContent ul.items li").click(function () {            
            var url = $(this).find('h3 a').attr('href');
            self._removeHash('section');
            self._loadPage(url);
            return false;
        });	

		$('#header #logo #description').click(function(){
			self._removeHash('section');
			self._removeHash('page');
			var section = $('#map div.open');
			self._closeSection(section);
			self._closePage();
			return false;
		});
        
        var hash = document.location.hash;
        self._loadHash(hash);		
		self._loadFacebook();
	}
	


    return {
        init: function () {
            //detect device => load css/js files
            //detect age cookies => load splash page => check theme cookies => load theme
           if ($('body').hasClass('inactive')) {
                self._ageValidation();
            } else {		
				self._loadTheme();

			}

           //doThisAfterLoadPage
        }, loadTheme: function (theme) {
            self._loadTheme(theme);
        }, loadSection: function (section) {
            self._loadSection(section);
        }, closeSection: function (section) {
            self._closeSection(section);
        }
    }
}();