function log(text){
  	if(typeof(console) != 'undefined'){
		console.log(text);
	};
  };
  
function getTags(id,range) {
	$.getJSON(
		'/index.php?eID=sig_frontend&what=getNGOTopics',
		function(data) {
			//$('#'+id).removeOption(/./);
			//$('#'+id).addOption({'0':'All'});
			
			for (i=0; i<data.length; i++) {
				if (typeof(range)!='undefined') {
					for (j=1; j<=range; j++) {
						$('#'+id+j).addOption(data[i].uid, data[i].value);
					}
				}
				else {
					$('#'+id).addOption(data[i].uid, data[i].value);
				}
			}
			
			if (typeof(range)!='undefined') {
				for (j=1; j<=range; j++) {
					
				
					
					$('#'+id+j).attr('disabled', null);
					$('#'+id+j).trigger("change")
					
				}
			}
			else {
				$('#'+id).selectOptions("0", true);
				$('#'+id).attr('disabled', null);
			}
		}
	);
}

function getIssues(id,tag,range) {
	var slot = (tag!=0)?parseInt(id.substr(id.length-1))-1 : -1;
	
	$.getJSON(
		'/index.php?eID=sig_frontend&what=getIssues&tag='+tag,
		function(data) {
			//var opts = $('#'+id).selectOptions(/);
			//$('#'+id).removeOption(/./); - /[^0-9]/
			$('#'+id).removeOption(/[^0]/);
			
			for (i=0; i<data.items.length; i++) {
				if (typeof(range)!='undefined') {
					for (j=1; j<=range; j++) {
						$('#'+id+j).addOption(data[i].uid, data.items[i].value);
					}
				} else {
					$('#'+id).addOption(data.items[i].uid, data.items[i].value);
				}
			}
			
			if (typeof(range)!='undefined') {
				for (j=1; j<=range; j++) {
					$('#'+id+j).selectOptions("0", true);
					$('#'+id+j).attr('disabled', null);
				}
			}
			else {
				$('#'+id).selectOptions("0", true);
				$('#'+id).attr('disabled', null);
			}
			
			
	
		}
	);
}

function getLocations(id,range) {
	
	$.getJSON(
		'/index.php?eID=sig_frontend&what=getLocationList',
		function(data) {
			for (i=0; i<data.length; i++) {
				if (typeof(range)!='undefined') {
					for (j=1; j<=range; j++) {
						$('#'+id+j).addOption(data[i].uid, html_entity_decode(data[i].value));
					}
				}
				else {
					$('#'+id).addOption(data[i].uid, html_entity_decode(data[i].value));
				}
			}
			
			if (typeof(range)!='undefined') {
				for (j=1; j<=range; j++) {
					$('#'+id+j).attr('disabled', null);
					
					
					
				}
			}
			else {
				$('#'+id).selectOptions("0", true);
				$('#'+id).attr('disabled', null);
			}
			
		}
	);
}

function init(){};

$(document).ready(function() {
				   
	$(".det").click(function(e){				
		e.preventDefault();
	
		// V t je shranjen trenutni.
		var t = {
			topic:$(this).parent().find(".topic").selectedValues()[0],
			issue:$(this).parent().find(".issue").selectedValues()[0],
			location:$(this).parent().find(".location").selectedValues()[0],
			range: $('.date').selectedValues()[0]
		};
		
		if(t.topic=="0"){
			alert("Select topic!");
			return true;
		};
		
		if(t.topic=="0" && t.issue=="0" && t.location=="0"){
			alert("Select topic, issue or region to see details.");
			return true;
		};
		
	
	//	document.location = 'index.php?id=34';
	
	
		//log(matrika);
		//alert("redirect...");
		
		window.location = '/index.php?id=archive';
	});

						  
	$('#topic1').change(function (){
		var opts = $(this).selectedValues();
		getIssues('issue1', opts);
	});
	
	$('#topic2').change(function (){
		var opts = $(this).selectedValues();
		getIssues('issue2', opts);
	});
	
	$('#topic3').change(function (){
		var opts = $(this).selectedValues();
		getIssues('issue3', opts);
	});
	
	//getTags('topic',3);
	//getIssues('issue',0,3);
	//getLocations('location',3);


	/*
	$('#display-chart').click(function(e) {
		e.preventDefault();
		
		var check = false;
		var data = new Array();
		data[0] = new Object();
		data[1] = new Object();
		data[2] = new Object();
		
		var i = 0;
		$('.topic').each(function(){
			var opt = $(this).selectedValues();

			if (opt!=0) check = true;
			
			data[i].topic = opt;
			
			if ($(this).selectedOptions().html() != 'All Topics')
				data[i].name = $(this).selectedOptions().html();
				
			i++;
		});
		
		i=0;
		$('.issue').each(function(){
			var opt = $(this).selectedValues();
			
			data[i].issue = opt;
			
			if ($(this).selectedOptions().html() != 'All Issues')
				data[i].name = $(this).selectedOptions().html();
				
			i++;
		});
		
		i=0;
		$('.location').each(function(){
			var opt = $(this).selectedValues();

			data[i].location = opt;
			
			if ($(this).selectedOptions().html() != 'All Regions')
				data[i].name += " / " + $(this).selectedOptions().html();
				
			i++;
		});
		
		if (check) {
			displayGraph($('.date').selectedValues(), data);
		}else {
			alert('Please select at least one topic!');
		}
	});
	*/
	
	var check = false;
	$('.topic').each(function(){
		var opt = $(this).selectedValues();

		if (opt!=0) check = true;
	});
	
	if (check) {
		var data = new Array();
		data[0] = new Object();
		data[1] = new Object();
		data[2] = new Object();
		
		var i = 0;
		$('.topic').each(function(){
			var opt = $(this).selectedValues();
			data[i].topic = opt;
			
			if ($(this).selectedOptions().html() != 'All Topics')
				data[i].name = $(this).selectedOptions().html();
				
			i++;
		});
		
		i=0;
		$('.issue').each(function(){
			var opt = $(this).selectedValues();
			
			data[i].issue = opt;
			
			if ($(this).selectedOptions().html() != 'All Issues')
				data[i].name = $(this).selectedOptions().html();
				
			i++;
		});
		
		i=0;
		$('.location').each(function(){
			var opt = $(this).selectedValues();

			data[i].location = opt;
			
			if ($(this).selectedOptions().html() != 'All Regions')
				data[i].name += " / " + $(this).selectedOptions().html();
				
			i++;
		});
		
		if (check) {
			displayGraph($('.date').selectedValues(), data);
		}
		else {
			alert('Please select at least one topic!');
		}
	}
	
	$(".details").click(function(e){
		e.preventDefault();
		index = $(this).attr('rel');
		
		topic = $("#topic" + index).selectedValues();
		issue = $("#issue" + index).selectedValues();
		region = $("#location" + index).selectedValues();
		
		if (topic!=0 || issue!=0 || region!=0) {
			url =  '/index.php?id=archive&si_Topic=' + topic + "&si_Issues=" + issue + "&si_Location=" + region + "&bButton=iTracker";
			window.location = url;
		}
		else
			return false;
	});

	/* Select problem */
	$("select").focus(function(){
		if($.browser.msie){
			$(this).attr("pz",$(this).width());
			$(this).width(300);
		};
	});

	$("select").change(function(){
		if($.browser.msie) $(this).width($(this).attr("pz"));
	});

	$("select").blur(function(){
		if($.browser.msie) $(this).width($(this).attr("pz"));
	});
	
	/* Save user search */
	$('#savesearch').click(function(e){
		e.preventDefault();
		/*
		 * $tag = array_shift($args);
		 * $issue = array_shift($args);
		 * $region = array_shift($args);
		 * $country = array_shift($args);
		 * $rows = array_shift($args);
		 * $keywords = array_shift($args);
		 */
		var user_id = $('input#user_id').val();
		var name = prompt("Name?", "");
		
		if (name!=null && name.length>0) {
			var type = 'issues_tracker';
			var topic1 = $('select[name="topic1"]').val();
			var issue1 = $('select[name="issue1"]').val();
			var region1 = $('select[name="location1"]').val();
			
			var topic2 = $('select[name="topic2"]').val();
			var issue2 = $('select[name="issue2"]').val();
			var region2 = $('select[name="location2"]').val();
			
			var topic3 = $('select[name="topic3"]').val();
			var issue3 = $('select[name="issue3"]').val();
			var region3 = $('select[name="location3"]').val();
			
			var date_range = $('select[name="date"]').val();
			
			var pid = $('input[name="id"]').val();
			
			url = '/index.php?eID=sigwatch_ws&f=addSearchFilter&c=userFilters&out=json';
			url += '&p_pid=' + pid;
			url += '&p_user_id=' + user_id;
			url += '&p_name=' + escape(name);
			url += '&p_type=' + type;
			url += '&p_topic1=' + topic1;
			url += '&p_issue1=' + issue1;
			url += '&p_region1=' + region1;
			url += '&p_topic2=' + topic2;
			url += '&p_issue2=' + issue2;
			url += '&p_region2=' + region2;
			url += '&p_topic3=' + topic3;
			url += '&p_issue3=' + issue3;
			url += '&p_region3=' + region3;
			url += '&p_date=' + date_range;
			
			$.getJSON(url, function(data){
				
				if (data.status ==  'name_exists') {
					//alert("A saved search named \""+data.name+"\" allready exists!");
					if (confirm("A saved search named \""+data.name+"\" already exists.\nDo you want to replace it?")) {
						url = '/index.php?eID=sigwatch_ws&f=updateSearchFilter&c=userFilters&out=json';
						url += '&p_pid=' + pid;
						url += '&p_user_id=' + user_id;
						url += '&p_type=' + type;
						url += '&p_name=' + escape(name);
						url += '&p_topic1=' + topic1;
						url += '&p_issue1=' + issue1;
						url += '&p_region1=' + region1;
						url += '&p_topic2=' + topic2;
						url += '&p_issue2=' + issue2;
						url += '&p_region2=' + region2;
						url += '&p_topic3=' + topic3;
						url += '&p_issue3=' + issue3;
						url += '&p_region3=' + region3;
						url += '&p_date=' + date_range;
						url += '&p_id=' + data.id;
			
						$.getJSON(url, function(data){
							alert("Your search was successfully saved!");
							document.location = data.url;
						});
					}
				}
				else if (data.status == 'search_exists')
					alert("This search was already saved as  \""+data.name+"\" !");
				else {
					alert("Your search was successfully saved!");
					document.location = document.location;
				}
			});
		}
		else if (name!=null) {
			alert('Please give your saved search a name!');
		}
	});
	
	$('select[name="saved_searches"]').change(function(){
		if (this.value>0) {
			pid = $('input[name="id"]').val();
			url = '/index.php?eID=sigwatch_ws&f=fetchSearchFilter&c=userFilters&out=json&p_pid='+pid+'&p_id=' + this.value;
			$.getJSON(url, function(data){
				document.location = data.url;
			});
		}
	});
	
	 //auto create chart on dropdown selection
	 $(".tracker .variable select").change(function() {
	         $(".tx-sigfrontend-pi4 form").submit();
        });
	                                 
	
});

function serialize( mixed_value ) {
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
};

function unserialize(data){
    var error = function (type, msg, filename, line){throw new window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;
        
        buf = [];
        for(var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;
 
        if(!offset) offset = 0;
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();
        
        var dataoffset = offset + 2;
        var typeconvert = new Function('x', 'return x');
        
        switch(dtype){
            case "i":
                typeconvert = new Function('x', 'return parseInt(x)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "b":
                typeconvert = new Function('x', 'return (parseInt(x) == 1)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "d":
                typeconvert = new Function('x', 'return parseFloat(x)');
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case "n":
                readdata = null;
            break;
            case "s":
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;
                
                readData = read_chrs(data, dataoffset+1, parseInt(stringlength));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if(chrs != parseInt(stringlength) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }
            break;
            case "a":
                readdata = {};         
                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;
                
                for(var i = 0;i < parseInt(keys);i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;
                    
                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;
                    
                    readdata[key] = value;
                }
                
                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    return _unserialize(data, 0)[2];
};

var bake_pdf = false;
var name_pdf = "";

function getPDF(){};
$(function(){	 
	$("#getPDF").click(function(e){				
			e.preventDefault();
			
			if(bake_pdf==true){ alert("PDF generation in progress. Please wait!"); return false; };
			bake_pdf = true;
			
			$(this).html("Making PDF. Please wait...");
			$("#pdfproc").show();
			
			var datap = { "graph" : serialize(graph_data),
				'info':serialize(graph_info),
				'date' : graph_date,
				'range': $("#date").selectedValues()[0],
				'imepage':'tracker' };
			
			$.post("/agpdf/index.php",  datap,
			  function(data){	
					log(data);
					bake_pdf=false;
					name_pdf = data.name;
					var currentTime = new Date();
					var month = currentTime.getMonth() + 1;
					var day = currentTime.getDate();
					var year = currentTime.getFullYear();
					var cname = "SIGWatch_Issues_Tracker-"+day+"_"+month+"_"+year+".pdf";

					window.location = "/agpdf/read.php?f="+name_pdf+"&n="+cname;
					$('#getPDF').html("Download PDF");
					$("#pdfproc").hide();					
			}, "json");
			
	});	   
});

