$(function () {
	
	$('.dropdown').each(function () {
		$(this).parent().eq(0).hoverIntent({
			timeout: 100,
			over: function () {
				$("#menu-o_programie").toggleClass('drop', 100);
				var current = $('.dropdown:eq(0)', this);
				current.fadeIn(10);
			},
			out: function () {
				$("#menu-o_programie").toggleClass("drop", 100);
				var current = $('.dropdown:eq(0)', this);
				current.fadeOut(200);
			}
		});
	});

	
	$('.dropdown li').hover(function () {
		$(this).stop(true).animate({paddingLeft: '20px'}, {speed: 100, easing: 'easeOutBack'});
	}, function () {
		$(this).stop(true).animate({paddingLeft: '10px'}, {speed: 100, easing: 'easeOutBounce'});
	});
});

function gaTrackPageView(url){
	if(typeof _gaq != 'undefined'){
		_gaq.push(['_trackPageview', url]);
	}
}

function loadImages(container){
	$.ajax({
		url: '/poster/get-posters',
		type: "POST",
		dataType: 'json',
		data: { ajax: true, amount: 3 },
		success: function (response, status){
				if(response.error){
					container.html('');
				}else{
					var images = $("<div/>");
					images.append('<ul class="preview-images"/>')
					for(var i in response){
						images.children('ul').append('<li><img src="' + response[i]['loc'] + '" alt="" /></li>');
					}
					container.html(images.html());
				}
		},
		error: function(){
			container.html('');
		}
	});
}

function initFancyBox(){
	$(".enlarge_image").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'hideOnContentClick' : true,
		'overlayColor' : '#81a200',
		'titlePosition' : 'inside',
		'titleFormat' : function (){
			return $(this.orig).parent().next().html();
		},
		'onComplete': function(){
			var clip = new ZeroClipboard.Client();
			
			$('#fancybox-title').find('.copy_button').attr('id', 'copy-button_current');
			$('#fancybox-title').find('.poster-link').attr('id', 'poster-link_current');

			clip.glue('copy-button_current');
			
			clip.addEventListener( 'mousedown', function(client) {
				clip.setText( $('#poster-link_current').val() );
			} );
		}
	});
}

function vote(poster){
	$.ajax({
		url: '/konkurs-na-plakat/glosuj/' + poster.attr('href'),
		type: "POST",
		dataType: 'json',
		data: { ajax: true, page: page, category: category },
		success: function (response, status){
			if(status == "success"){
				if(response.error){
				}else{
					if(response.success == true){
						$('.vote').removeClass('vote').addClass('voted').removeAttr('href');
						var votes = parseInt(poster.parent().parent().find('.poster-votes').children('span').html());
						poster.parent().parent().find('.poster-votes').children('span').html(votes+1);
						alert('Dziękujemy za oddanie głosu.');
					}else{
						alert('Z tego adresu IP został już oddany głos w tej kategorii. Zapraszamy jutro.');
					}
				}
			}
		}
	});
}

function posterSearch(query){
	if(query.length > 0){
		$.ajax({
			url: 'poster/search',
			type: "POST",
			dataType: 'json',
			data: { query: query },
			success: function (response, status){
				if(status == "success"){
					if(response.error){
					}else{
						if(typeof response.img != 'undefined'){
							var elem = $('<a href="' + response.img + '"/>');
							$('body').append(elem);
							elem.fancybox({
								'transitionIn'	:	'elastic',
								'transitionOut'	:	'elastic',
								'hideOnContentClick' : true,
								'overlayColor' : '#81a200',
								'titlePosition' : 'inside',
								'titleFormat' : function (){
									return response.title;
								},
								'onComplete': function(){
									var clip = new ZeroClipboard.Client();
									
									$('#fancybox-title').find('.copy_button').attr('id', 'copy-button_current');
									$('#fancybox-title').find('.poster-link').attr('id', 'poster-link_current');

									clip.glue('copy-button_current');
									
									clip.addEventListener( 'mousedown', function(client) {
										clip.setText( $('#poster-link_current').val() );
									} );
								}
							});
							elem.trigger('click');
						}else{
							alert('Szukana praca nie została znaleziona. Poprawny format numeru zgłoszenia to np. GR1-000');
						}
					}
				}
			}
		});
	}
}

function posterGoToPage(){
	var page = $('input[name="page"]').val();
	page = parseInt(page);
	if(page > 0 && page < 200){
		var url = window.location.href;
		window.location = url.replace(/strona,\d+\./, "strona,"+parseInt(page)+".");
	}
}

function voteInit(){
	$('.vote').live('click', function(){
		vote($(this));
		
		return false;
	});
	
	$('#poster-search_button').click(function(){
		posterSearch($(this).prev().val());
		
		return false;
	});
	
	$('#poster_page_button').click(function(){
		posterGoToPage();
		
		return false;
	});
	
}

/*
 * WLASCIWA FUNKCJA DO PUBLIKOWANIA NA WALLU
 * @movieTitle - tytul filmu
 * @movieAdress - link do filmu na stronie
 * @displayName - tekst wyswietlany w filmie
 */

function shareMovie(movieTitle, movieAdress, displayName) 
{
	
	FB.ui({
		method: 'feed',
		name: movieTitle,
		link: movieAdress,
		picture: 'http://static.postronienatury.pl/images/wall_ico.jpg',
		source: baseUrl + '/flash/film_name.swf?displayName=' + displayName,
		caption: '{*actor*} już wie. Ty też sprawdź co usłyszysz, kiedy posadzisz jedno drzewo. Posadź z nami milion drzew!',
		description: '',
		message: '',
		actions: [
		          { name: 'Posadź drzewo', link: baseUrl + '/posadz-drzewo.html' }
		]
	});
}

/**
 * Checks if the given value exists in the array  
 * 
 * version: 1006.1915
 * discuss at: http:*phpjs.org/functions/in_array    * +   original by: Kevin van Zonneveld (http:*kevin.vanzonneveld.net)
 * +   improved by: vlado houba
 * +   input by: Billy
 * +   bugfixed by: Brett Zamir (http:*brett-zamir.me)
 * *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    * *     returns 1: true
 * *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
 * *     returns 2: false
 * *     example 3: in_array(1, ['1', '2', '3']);
 * *     returns 3: true    * *     example 3: in_array(1, ['1', '2', '3'], false);
 * *     returns 3: true
 * *     example 4: in_array(1, ['1', '2', '3'], true);
 * *     returns 4: false
 */
function in_array(needle, haystack, argStrict){
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
}

/**
* Simulate php array_merge function
*
* ... [more] * @param {Object/Array} arr1
* @param {Object/Array} arr2
* var a1 = {'aa':100, 'bb':2, 'cc':[6,7], 'dd':[12,13], 'ee':{'15':15,'16':16}};
* var b1 = {'xx':101, 'bb':5, 'cc':8, 'dd':[14,15], 'ee':{'17':17,'18':18}};
* var c = array_merge(a1, b1);
* console.log(c) [in firebug]
* Output: {'aa':100, 'bb': 5, 'cc':[6,7], 'dd':[12,13,14,15], 'ee':{'15':15,'16':16,'17':17,'18':18}, 'xx':101}
*/
var array_merge = function(arr1, arr2){
  if((arr1 && (arr1 instanceof Array)) && (arr2 && (arr2 instanceof Array))){
    for (var idx in arr2) {
      arr1.push(arr2[idx]);
    }
  }else if((arr1 && (arr1 instanceof Object)) && (arr2 && (arr2 instanceof Object))){
    for(var idx in arr2){
      if(idx in arr1){
        if (typeof arr1[idx] == 'object' && typeof arr2 == 'object') {
          arr1[idx] = array_merge(arr1[idx], arr2[idx]);
        }else{
          arr1[idx] = arr2[idx];
        }
      }else{
        arr1[idx] = arr2[idx];
      }
    }
  }
  return arr1;
}

/**
 * Replace [ with \[ and ] with \]
 * 
 * @param string name
 * @return string
 */
function normalizeName(name){
	name = name.replace(/\[/g, '\\[');
	name = name.replace(/\]/g, '\\]');
	
	return name;
}



