var globalMainOpacity = 0.7;
var globalFadeTime = 1000;

$(document).ready(function()
{
	introStart();
	initIntro();
	initMainMenu();
	
	externalLinks();

	makeHoverable('#menu-main, #lang-ro, #lang-en', [ globalMainOpacity, 1 ]);
	makeHoverable('#footer a', [ 0.3, 1 ]);
	makeHoverable('#head-left', [ 1, globalMainOpacity ]);
	makeHoverable('#head-left-en', [ 1, globalMainOpacity ]);

	$('#head-left, #head-left-en').click(function()
	{
		window.location = 'index.php?page=intro';
	});

	$('.gallery a').lightBox();
	$('.gallery2 a').lightBox();

	initAlbum();
	initYT();
	
	$('div.content-sep-line a').click(function(e)
	{
		$.scrollTo( 0, 1000, { easing:'easeInOutCubic'});
		e.preventDefault();
		return false;
	});
	
	$('.scroll a').click(function(e)
	{
		var href = 'a[name='+ $(this).attr('href').substring(1) + ']';
		$(window).scrollTo( href, 1000, { easing:'easeInOutCubic'});
		e.preventDefault();
		return false;
	});
	
});

function initYT()
{
	$('.linkyoutube')
	        .click(
	                function(e)
	                {
		                // http://www.youtube.com/v/UbueSiV3te8?autoplay=1
		                // <?php print GetHtml_YouTubeExtra("v/sCvK6i7VSzc",
		                // "autoplay=1", "640", "505");

		                var width = 640;
		                var height = 480;
		                var url = $(this).attr('href');
		                if (url.indexOf('http://www.youtube.com') != 0)
		                {
			                return true;
		                }
						var dic = {};
						if( getLanguage() == 'en')
						{
							dic['yt-legend'] = 'Click ouside the videoclip to close this screen.<br/>'
		                        + 'Double click on the videoclip to play fullscreen.<br/>'
		                        + 'Mouse over the videoclip for more options.';
						}
						else
						{
							dic['yt-legend'] = 'Click in exteriorul videoclipului pentru inchiderea acestui ecran.<br/>'
		                        + 'Dublu click pe videoclip pentru redare pe tot ecranul (fullscreen).<br/>'
		                        + 'Pozitionati mouse-ul peste videoclip pentru mai multe comenzi.';
						}
						
		                var html = ""
		                        + '<div class="playerintro" id="ytplayer">'
		                        + '<p class="playerintro-info signature">'
		                        + '<a href="#" class="playerinfo">' + dic['yt-legend'] + '</a>' 
								+ '</p>'
		                        + '<div style="position:relative; margin:0 auto; width:'
		                        + width
		                        + 'px; height:'
		                        + height
		                        + 'px;">'
		                        + '<object width="'
		                        + width
		                        + '" height="'
		                        + height
		                        + '">'
		                        + '<param name="movie" value="'
		                        + url
		                        + '"></param>'
		                        + '<param name="allowFullScreen" value="true"></param>'
		                        + '<param name="allowscriptaccess" value="always"></param>'
		                        + '<embed src="'
		                        + url
		                        + '" '
		                        + 'type="application/x-shockwave-flash" '
		                        + 'allowscriptaccess="always" '
		                        + 'allowfullscreen="true" '
		                        + 'width="'
		                        + width
		                        + '" '
		                        + 'height="'
		                        + height
		                        + '">'
		                        + '</embed>' + '</object>' + '</div>' + '</div>';

		                $(html).appendTo('body');
		                var $clone = $('#ytplayer');
		                $clone.css(
		                {
		                    width : $(window).width(),
		                    height : Math.max($(window).height(), $(document).height()),
		                    opacity : 0.95,
		                    paddingTop : $(window).scrollTop()
		                }).show().click(function(e)
		                {
			                $clone.remove();
		                });

		                return false;
	                });
}

function makeHoverable(selector, opacity)
{
	$(selector).hover(function()
	{
		$(this).animate(
		{
			'opacity' : opacity[1]
		});
	}, function()
	{
		$(this).animate(
		{
			'opacity' : opacity[0]
		});
	}).css('opacity', opacity[0]);

}

function initMainMenu()
{
	$("#menu-main").lavaLamp(
	{
	    fx : "easeOutBack",
	    speed : 700,
	    click : function(event, menuItem)
	    {
		    // return false;
	    }
	});
}

function initIntro()
{
	$('div.main div').css(
	{
		'opacity' : globalMainOpacity
	}).hover(function()
	{
		$(this).animate(
		{
			'opacity' : 1
		});
	}, function()
	{
		$(this).animate(
		{
			'opacity' : globalMainOpacity
		});
	}).click(function(e)
	{
		$(this).bind('mouseleave', mouseleave2).animate(
		{
			'opacity' : 0
		}, globalFadeTime, function()
		{
			$(this).css(
			{
			    backgroundImage : 'none',
			    backgroundColor : '#222'
			}).html($('#htext').html()).animate(
			{
				'opacity' : globalMainOpacity
			}, globalFadeTime);
		});

		return false;
	});

	$('#introclip, .intro').click(function(e)
	{
		introPause();
		var $clone = $('.playerintro').clone();
		$clone.appendTo('body');
		$clone.css(
		{
		    width : $(window).width(),
		    height : Math.max($(window).height(), $(document).height()),
		    opacity : 0.95
		}).show().click(function(e)
		{
			$clone.remove();
			introResume();
		});
		return false;
	});
}

function mouseleave2(e)
{
	var self = e.target;
	$(this).unbind('mouseleave', mouseleave2);

	$(self).animate(
	{
		'opacity' : 0
	}, globalFadeTime, function()
	{
		$(self).css(
		{
		    backgroundImage : '',
		    backgroundColor : ''
		}).html('').animate(
		{
			'opacity' : globalMainOpacity
		}, globalFadeTime);
	});
}

function introStart()
{
	$('.intro').each(function(index)
	{
		$(this).cycle(
		{
		    fx : 'fade',
		    timeout : 5000,
		    speed : 1500,
		    delay : index * 1000
		});
	});
}

function introPause()
{
	$('.intro').cycle('pause');
}

function introResume()
{
	$('.intro').cycle('resume');
}

function replaceInElement(element, find, replace)
{
	// iterate over child nodes in reverse, as replacement may increase
	// length of child node list.
	for ( var i = element.childNodes.length; i-- > 0;)
	{
		var child = element.childNodes[i];
		if (child.nodeType == 1)
		{ // ELEMENT_NODE
			var tag = child.nodeName.toLowerCase();
			if (tag != 'style' && tag != 'script') // special case, don't touch
				// CDATA elements
				replaceInElement(child, find, replace);
		}
		else if (child.nodeType == 3)
		{ // TEXT_NODE
			replaceInText(child, find, replace);
		}
	}
}
function replaceInText(text, find, replace)
{
	var match;
	var matches = [];
	while (match = find.exec(text.data))
		matches.push(match);
	for ( var i = matches.length; i-- > 0;)
	{
		match = matches[i];
		text.splitText(match.index);
		text.nextSibling.splitText(match[0].length);
		text.parentNode.replaceChild(replace(match), text.nextSibling);
	}
}

function imageTooltip(selector, src)
{
	var offsetX = offsetY = 10;
	$(selector).hover(function(e)
	{
		$('body').append('<div id="imagetooltip"><img src="' + src + '" alt=""/></div>');
		$('#imagetooltip img').load(function(e)
		{
			var $this = $(this);
			// window.console.log( $this.width() + ',' +
			// $this.height());

			$('#imagetooltip').animate(
			{
			    width : $this.outerWidth(),
			    height : $this.outerHeight()
			}, 200, function()
			{
				$this.fadeIn(200);
			});
		});

		$('#imagetooltip').css(
		{
		    'left' : e.pageX + offsetX,
		    'top' : e.pageY + offsetY,
		    'display' : 'block',
		    'opacity' : 0
		}).animate(
		{
			'opacity' : 1
		}, 500);
	}, function(e)
	{
		$("#imagetooltip").remove();
	});
}

function initDogLinks()
{
	$(document).ready(function()
	{
		/*
		 * // keywords to match. This *must* be a 'g'lobal regexp or it'll fail
		 * bad var find = [ /\b(Bonjuk)\b/gi, /\b(Concetta)\b/gi,
		 * /\b(Dixy)\b/gi, /\b(Kara)\b/gi, // /\b(Max)\b/gi, /\b(Maura)\b/gi,
		 * /\b(Seth)\b/gi, /\b(Sissy)\b/gi, /\b(Team)\b/gi, /\b(Porto)\b/gi,
		 * /\b(Summy)\b/gi ]; // replace matched strings with ... for( var i=0;
		 * i<find.length; i++) { replaceInElement( document.body, find[i],
		 * function(match) { var link = document.createElement('a');
		 * link.className = 'dogtooltip'; link.href = '#' + match[0];
		 * link.appendChild(document.createTextNode(match[0]));
		 * imageTooltip(link, 'images/face/'+match[0]+'.jpg'); return link; }); }
		 */
		$('.dogtooltip').each(function()
		{
			var href = $(this).attr('href');
			var dogname = href.substring(href.indexOf('#') + 1).toLowerCase();
			imageTooltip(this, 'images/face/' + dogname + '.jpg');
		});
	});
}

function initAlbum()
{
	// makeHoverable('.album li', [0.8, 1]);

	$('.album li').hover(function()
	{
		$(this).addClass('hover');
	}, function()
	{
		$(this).removeClass('hover');
	}).click(function()
	{
		window.location = $(this).find('a:first').attr('href');
	});

	if (!$.browser.msie)
	{
		$('.album li').css(
		{
			backgroundImage : 'url(images/album-bkg.png)'
		});
	}
}

function changecss(theClass, element, value)
{
	var cssRules;
	var added = false;
	for ( var S = 0; S < document.styleSheets.length; S++)
	{

		if (document.styleSheets[S]['rules'])
		{
			cssRules = 'rules';
		}
		else if (document.styleSheets[S]['cssRules'])
		{
			cssRules = 'cssRules';
		}
		else
		{
			// no rules found... browser unknown
		}

		for ( var R = 0; R < document.styleSheets[S][cssRules].length; R++)
		{
			if (document.styleSheets[S][cssRules][R].selectorText == theClass)
			{
				if (document.styleSheets[S][cssRules][R].style[element])
				{
					document.styleSheets[S][cssRules][R].style[element] = value;
					added = true;
					break;
				}
			}
		}
		if (!added)
		{
			try
			{
				document.styleSheets[S].insertRule(theClass + ' { ' + element + ': ' + value + '; }',
				        document.styleSheets[S][cssRules].length);

			}
			catch (err)
			{
				try
				{
					document.styleSheets[S].addRule(theClass, element + ': ' + value + ';');
				}
				catch (err)
				{
				}

			}

			// if(document.styleSheets[S].insertRule){
			// document.styleSheets[S].insertRule(theClass+' { '+element+':
			// '+value+'; }',document.styleSheets[S][cssRules].length);
			// } else if (document.styleSheets[S].addRule) {
			// document.styleSheets[S].addRule(theClass,element+': '+value+';');
			// }
		}
	}
}

function externalLinks()
{
	if (!document.getElementsByTagName)
		return;
		
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++)
	{
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}

function getLanguage()
{
	var lang = $('html').attr('lang');
	return lang.length ? lang : 'ro';
}
