/**
 * Base JavaScript File
 */

$(document).ready(function() {
	/**************************** POOL START */
	var _id 		= $("#poll_id").val();
	
	if($("#poll_active").val() == 0)
	{
		poolAnimate();
	} 
	else {
		$('#poll').children('li').click(function(e) {
			$(this).children('input:radio:nth(0)').attr("checked","checked");
			var cb = ($(this).children('input:checkbox').attr("checked") == true) ? false : true;
			$(this).children('input:checkbox').attr("checked", cb);
		});	
	}
	//$("body").click(UpdateClickMap);
});
function enter_pressed(e){
	var keycode;
	if (window.event) keycode = window.event.keyCode; 
	else if (e) keycode = e.which; 
	else return false; 
	return (keycode == 13); 
}

function szukaj() {
	document.getElementById('searchBox').value = prepareWords(document.getElementById('searchBox').value)
	var words = (document.getElementById('searchBox').value);
	
	if(words.length < 3)
	{
		alert('Twoja fraza wyszukiwania jest za krótka, słowo musi mieć conajmniej 3 znaki');
	} else {
		var query = words.replace(/[ ]+/gi, '+');
		window.location = "http://tvkanon.pl/wyszukaj," + query  + ".html";
	}
	//window.location = "http://tvkanon.pl/new2/wyszukaj," + words + ".html";	
}

/**************************** AJAX SUBMIT POOL FORM */
function pollSubmit(type)
{
	
	var _id 		= $("#poll_id").val();
	if(pokazCookie('ankieta'+_id) == undefined)
	{
		
		var answers = new Array();
		var answer 	= false;
		
		for(i=1; i<=12; i++){
			
			var id = $("#li"+i).children("input").attr("id");
			var val = $("#li"+i).children("input").attr("checked");
			answers[i] = new Array(id, val);
			
			if($("#li"+i).children("input").attr("checked") == true) {
				var answer 	= true;
			}
			
		}
		
		if(answer){
			//alert(answer);
			$.ajax({
				url			: "class/getPoll.php",
				global		: false,
				type		: "GET",
				data		: ({	
					ajax_vote		: 1,
					poll_id 		: _id,
					votes			: answers
				}),
				dataType: "html",
				success: function(html){
					if(html == 'Dziękujemy za głos'){
						alert(html);
						showResult(_id);
						
						var teraz = new Date();
						teraz.setDate(teraz.getDate()+30);
						ustawCookie('ankieta'+_id, '1', teraz);
						//alert(pokazCookie('ankieta'+_id)+','+ 'ankieta'+_id);
						
					} else {
						alert(html);
					}
				}
			});
		} else {
			if(type != 0){
				alert('Proszę wybrać jedno lub więcej pól');
			} else {
				alert('Proszę wybrać jedno z pól');
			}
		}
	} else {
		alert('Oddałeś już głos w tej ankiecie');
	}
}

/**************************** AJAX GET POOL RESUNTS */
function showResult(id){
	//alert('pokazuje ankietę ' + id);	
	
	$.ajax({
		url			: "class/getPoll.php",
		global		: false,
		type		: "GET",
		data		: ({	
			ajax_resault	: 1,
			poll_id 		: id,
		}),
		dataType: "html",
		success: function(html){
			var w = Number($("#poll").innerWidth());
			$('#poll').css('height', $('#poll').height());
			$('#poll').animate({width:'1'}, 'normal', function(){
				$('#poll').empty();
				$('#poll').append(html);
				$('#poll').css("width", '0px');
				$('#poll').css("width", w);
				
				poolAnimate();				
			});
			
			
			//alert($('#poll').css('opacity'));
			//$('poll').children('ul').append(html);
			//$('poll').children('ul').animate({opacity: 1}, "normal");
		}
	});
	
}

/**************************** ANIMATION POOL RESUNTS */
function poolAnimate(){
	$('.pollSubmit').remove();
	$('.showVotes').remove();
	
	var max = Number($("#poll").innerWidth()) - 6;
	for(i=1; i<=12; i++){
		var val = Number($("#pod_li"+i).attr("rel")) * max;
		$("#pod_li"+i).delay(i*50).animate({width:val}, "slow");
	}
}

/**************************** URL TRACKER */
function trackURL(click){
	$.ajax({
		url			: "class/urlTracker.php",
		global		: false,
		type		: "GET",
		data		: ({	
			ajax_track		: 1,
			click 			: click,	  	
		}),
		dataType: "html",
		success: function(html){
		}
	});
}

function clearDiacritics(sText)  
{  
    var aReplacePL = new Array();  
    aReplacePL['ą'] = 'a';
    aReplacePL['ę'] = 'e';
    aReplacePL['ś'] = 's';
    aReplacePL['ć'] = 'c';
    aReplacePL['ó'] = 'o';
    aReplacePL['ń'] = 'n';
    aReplacePL['ż'] = 'z';
    aReplacePL['ź'] = 'z';
    aReplacePL['ł'] = 'l';
    aReplacePL['Ą'] = 'A';
    aReplacePL['Ę'] = 'E';
    aReplacePL['Ś'] = 'S';
    aReplacePL['Ć'] = 'C';
    aReplacePL['Ó'] = 'O';
    aReplacePL['Ń'] = 'N';
    aReplacePL['Ż'] = 'Z';
    aReplacePL['Ź'] = 'Z';
    aReplacePL['Ł'] = 'L';
      
    //alert(str_replace(' ', '.', 'Kevin van Zonneveld'));
    //alert("str_replace("+array_keys(aReplacePL)+", "+array_values(aReplacePL)+", sText)");
    return str_replace(array_keys(aReplacePL), array_values(aReplacePL), sText);  
}  
  
function prepareWords(sText)  
{
	//alert('szukam')
	//sText = clearDiacritics(sText);
	sText = sText.toLowerCase();
	//alert(sText);
	sText = sText.replace(/[^0-9a-zęółąśżźćńĘÓŁĄŚŻŹĆŃ ]+/, '');
	//alert(sText);
	return sText;
}

function trim (str, charlist) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: DxGx
    // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6

    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function array_values (input) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_values( {firstname: 'Kevin', surname: 'van Zonneveld'} );
    // *     returns 1: {0: 'Kevin', 1: 'van Zonneveld'}

    var tmp_arr = [], cnt = 0;
    var key = '';

    for ( key in input ){
        tmp_arr[cnt] = input[key];
        cnt++;
    }

    return tmp_arr;
}
function array_keys (input) {
	var tmp_arr = [], cnt = 0;
    var key = '';
    for ( key in input ){
        tmp_arr[cnt] = key;
        cnt++;
    }
    return tmp_arr;
}
function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

/**************************** COOKIE ACTIONS */
function ustawCookie(nazwa, wartosc, expire) {
	document.cookie = nazwa + "=" + escape(wartosc) + ((expire==null)?"" : ("; expires=" + expire.toGMTString()))
}
function pokazCookie(nazwa) { 
	if (document.cookie!="") { 
	var toCookie=document.cookie.split("; ");  
		for (i=0; i<toCookie.length; i++) {
			var nazwaCookie=toCookie[i].split("=")[0];
			var wartoscCookie=toCookie[i].split("=")[1]; 
			if (nazwaCookie==nazwa) return unescape(wartoscCookie);
		}
	}
}

