
var cookie_prefix = "szp_";
var names = ['iop', 'nshp', 'numunk', 'numempty', 'shwdrop', 'shwstats' ];
var def_names = ['50', '', true, true, false, true ];
var checkboxes = [ 'numunk', 'numempty', 'shwdrop', 'shwstats' ];

var search_timer = null;
var search_timer_timeout = 1000;
var search_async_number = 0;

var search_output_div = "#search_result_box";
var search_progress_div = "#search_progress_box";
var search_error_div = "#ajax_search_error";

function resetAll() {
	//$("input").checked = false;
	document.getElementById("cat_all").checked=false;
}

function resetRest() {
	var elements = document.getElementsByName("cat");
	//alert('liczba elementow: ' + elements.length);
	for (var i=0;i<elements.length;i++) {
		elements[i].checked = false;
	}
	document.getElementById("cat_all").checked=true;
}

function getFlashVersion() { 
  // ie 
  try { 
    try { 
      // avoid fp6 minor version lookup issues 
      // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ 
      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
      try { axo.AllowScriptAccess = 'always'; } 
      catch(e) { return '6,0,0'; } 
    } catch(e) {} 
    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
  // other browsers 
  } catch(e) { 
    try { 
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
      } 
    } catch(e) {} 
  } 
  return '0,0,0'; 
}

function is_flash_version_proper() {
    var result = 0;
    
    var rawFlashVersion = getFlashVersion();
    var flashVersion = rawFlashVersion.split(',');    

    if (flashVersion[0] > 9) {
        result = 1;
    } else if (flashVersion[0] == 9) {
        if (flashVersion[1] > 0) {
            result = 1;
        } else if (flashVersion[2] > 45) {
            result = 1;
        }	
    }
    
    return result;
}

function parse_date ( dataArray ) {
        var dataLength = dataArray.length;
        for(var i = 0; i < dataLength; i++) {
                var dataObj = dataArray[i];
                var splited = dataObj.day.split("-");
                dataObj.properDate = splited[1] + "/" + splited[2] + "/" + splited[0];

                if (dataObj.number == "?") {			
                        dataObj.nav = 0;
                        dataObj.unk = 0;
                        dataObj.av = 0;
                } else if (dataObj.number < 0) {
                        dataObj.nav = 0;
                        dataObj.unk = 1;
                        dataObj.av = 0;
                } else if (dataObj.number == 0) {
                        dataObj.nav = 1;
                        dataObj.unk = 0;
                        dataObj.av = 0;				
                } else {
                        dataObj.nav = 0;
                        dataObj.unk = 0;
                        dataObj.av = 1;
                }
        }
        return dataArray; 
}	

function settings_save() {		
	for (var i=0;i<names.length;i++) {
		var name = names[i];			
		var obj = document.getElementById(name);
		var value = obj.value;	

		for (var c in checkboxes) {				
			if (checkboxes[c] == name) {					
				value = obj.checked;
			}
		}					
		
		make_cookie(cookie_prefix + name, value, cookie_time);
	}
	
	alert('Opcje zostały zapisane.');
}

function settings_reset() {
	for (var i=0;i<names.length;i++) {
		var name = names[i];
		make_cookie(cookie_prefix +name, "", -1);
		
		var obj = document.getElementById(name);
		var found = false;
		for (var c in checkboxes) {				
			if (checkboxes[c] == name) {					
				obj.checked = def_names[i];
				found = true;
				break;
			}
		}	
		if (!found) {
			obj.value = def_names[i];
		}			
	}
	settings_save();
}	

function make_cookie(name, value, days) {
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var date_string = date.toGMTString();
	
	var cookie = name+"="+value+"; " + date_string +"; path=/";
		
	document.cookie = cookie;
}	

function settings_restore() {
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var cookie = ca[i];
		
		while (cookie.charAt(0)==' ') 
			cookie = cookie.substring(1,cookie.length);

		
		var tmp_c = cookie.split('=');
		
		if (tmp_c[0].indexOf(cookie_prefix) == 0) {
			var name = tmp_c[0].replace(cookie_prefix, '');
			var value = tmp_c[1];

			var obj = document.getElementById(name);
			obj.value = value;
			
			if (obj.checked != null) {
				//alert("nazwa: " + name + " v: " + obj.value + " , v: " + obj.checked + "; value: " + value);
				if (value == "true") {
					obj.checked = true;						
				} else if (value = "false") {
					obj.checked =  false;						
				} 	
			}		
		} 
	}
}

function check_show_stats() {
	var result = true;
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var cookie = ca[i];
		
		while (cookie.charAt(0)==' ')
			cookie = cookie.substring(1,cookie.length);

		var tmp_c = cookie.split('=');
			
		if (tmp_c[0].indexOf('szp_shwstats') == 0) {			
			result = tmp_c[1];
		}
	}
	
	return result;
}

function prepare_page_for_results() {
	var timeout = 400;
	var elements_to_hide = [
		"#main_logo_box",
		"#stats_box",
		".main_news"		
	];
	var elements_to_show = [
		"#main_logo_box_small",
		search_output_div
	];
	
	if ($(elements_to_hide[0]).is(":visible")){		
		for (var i=0;i<elements_to_hide.length;i++) {
			var element_name = elements_to_hide[i];
			$(element_name).hide(timeout);
		}
		
		for (var i=0;i<elements_to_show.length;i++) {
			var element_name = elements_to_show[i];
			$(element_name).show(timeout);
		}	
	}
}

function update_search_timer() {
	if (search_timer != null) {
		clearTimeout(search_timer);		
		search_timer = null;	
	}	
	search_timer = setTimeout(update_search_results, search_timer_timeout);
}

function update_search_results() {
	var query = $("#q")[0].value;
	if (query != null && query.length >= 2) {
		prepare_page_for_results();		
		show_search_progess();		
		
		var categories = get_current_categories();	
		
		get_search_results(query, categories);
	} else if (query != null && query.length == 0) {
		$(search_output_div)[0].innerHTML = "";				
	}
}

function get_search_results(query, categories) {
	var query_data = "q=" + query;
	for (var i=0;i<categories.length;i++) {
		query_data += "&cat=" + categories[i];
	}
	search_async_number++;
	$(search_output_div).load("/ajax/search", query_data, function(responseText, textStatus, XMLHttpRequest) {
		search_async_number--;
		if (textStatus == "success") {
			//wszystko ok, to w sumie nie trzeba nic robic ;D			
		} else {
			search_results_error(textStatus);
		}
						
		hide_search_progess();		
	});
}

function get_current_categories() {
	var result = [];
	var categories_elements = $('input[name="cat"]');
	for (var i=0;i<categories_elements.length;i++) {
		var element = categories_elements[i];
		if (element.checked && element.value != -1) {
			result.push(element.value);
		}
	}
	
	return result; 
}

function show_search_progess() {
	if ($(search_progress_div).is(":hidden")) {
		$(search_progress_div).show();
	}
	$("#q").HideAllBubblePopups()
}

function hide_search_progess() {
	if ($(search_progress_div).is(":visible")) {
		if (search_async_number==0) {
			$(search_progress_div).hide();
		}
	}
}

function search_results_error(error) {	
	if ($(search_error_div).is(":hidden")) {
		$(search_error_div)[0].innerHTML = "Wystąpił błąd: " + error;
		$(search_output_div)[0].innerHTML = "";
		$(search_error_div).show();
	}
}


function search_item_bubble_creator(prod_id, image_url) {
	var max_width = 200;
	var max_height = 200;
	var selector = "#prod_" + prod_id;
	var options = {
	  innerHtml: '<div style="width: 200px;height:200px;display:table-cell;vertical-align: middle;"><div class="loading_box" id="loading_'+prod_id+'" /><img class="resizable_image" id="img_'+prod_id+'" src="'  +  image_url  + '" alt="Obrazek" /></div>',
		themePath : '/static/css/jquerybubblepopup-theme/',
		position: "right",		
		//height : "200px",
		//width : "300px",
		afterShown : function() {	
			resize_image_after_load("img_"+prod_id, max_width, max_height, "loading_"+prod_id);
		}
	};	
	
	if (! $(selector).HasBubblePopup() && image_url.length > 3) {
		$(selector).CreateBubblePopup(options);
	}	
}

function resize_image_after_load(elementId, max_width, max_height, hideElementAfterElementId) {
    //if ($.browser.opera) {
    
    var background_loaded_img_url = $("#"+elementId)[0].src;
    
    if ($.browser.opera || $.browser.mozilla || $.browser.msie) {        
        $("body").append("<img id='hidden_img'>");
        var hiddenImg = $("#hidden_img")[0];
        
        /*
        $("#hidden_img").attr({
            top: "-1000px",
            left: "-1000px"
        });
        */
        $("#hidden_img").css("top", "-1000px");
        $("#hidden_img").css("left", "-1000px");
        $("#hidden_img").css("position", "absolute");
        
        
        hiddenImg.onload = function(){
            var width = this.width;
            var height = this.height;
            var resized = resize_image(width, height, max_width, max_height);
            
            var new_width = resized[0];
            var new_height = resized[1];
            
            _do_image_resize(elementId, new_width, new_height, hideElementAfterElementId);
            
            $("#hidden_img").remove();
        }
        
        /*.bind('load', function() {
            var width = hiddenImg.width;
            var height = hiddenImg.height;
            var resized = resize_image(width, height, max_width, max_height);
            $("#"+elementId).attr('width', resized[0]);
            $("#"+elementId).attr('height', resized[1]);
            
            if (hideElementAfterElementId != null) {		
                $("#"+hideElementAfterElementId).hide();
            }
            $("#"+elementId).show();
        });
        */
       
        hiddenImg.src = background_loaded_img_url;
        
        /*
        var i = 0;
        
        var tmpImg = new Image();
        tmpImg.id = "hidden_img";
        tmpImg.onload = function(){
            var width = this.width;
            var height = this.height;
            var resized = resize_image(width, height, max_width, max_height);
            
            var new_width = resized[0];
            var new_height = resized[1];
            
            _do_image_resize(elementId, new_width, new_height, hideElementAfterElementId);   
        }
        tmpImg.src = $("#"+elementId)[0].src;
    */
    } else if ($.browser.webkit) {
        $("body").append("<img id='hidden_img'>");
        var hiddenImg = $("#hidden_img")[0];
        
        $("#hidden_img").css("top", "-1000px");
        $("#hidden_img").css("left", "-1000px");
        $("#hidden_img").css("position", "absolute");
        
        hiddenImg.addEventListener("load", function() {
            var width = this.naturalWidth;
            var height = this.naturalHeight;
            var resized = resize_image(width, height, max_width, max_height);
            
            var new_width = resized[0];
            var new_height = resized[1];
            
            _do_image_resize(elementId, new_width, new_height, hideElementAfterElementId);
            
            $("#hidden_img").remove();
        });
        
        hiddenImg.src = background_loaded_img_url;
        
    } else {
        if (hideElementAfterElementId != null) {		
            $("#"+hideElementAfterElementId).hide();
        }
        $("#"+elementId).show();	
        /*
	$("#"+elementId).bind('load', function (e) {		
		
            var width = $("#"+elementId).attr('width');
            var height = $("#"+elementId).attr('height');
            
            var resized = resize_image(width, height, max_width, max_height);
            
            var new_width = resized[0];
            var new_height = resized[1];
            
            _do_image_resize(elementId, new_width, new_height, hideElementAfterElementId);                                   
	});
        */
    }

}

function _do_image_resize(elementId, width, height, hideElementAfterElementId) {
    $("#"+elementId).attr('width', width);
    $("#"+elementId).attr('height', height);
    
    if (hideElementAfterElementId != null) {		
            $("#"+hideElementAfterElementId).hide();
    }
    $("#"+elementId).show();	
}

function resize_image(width, height, max_width, max_height) {
	var new_width = width;
	var new_height = height;	
	
	if (new_width > max_width) {
		new_width = max_width;
		var ratio = new_width / width;
		
		new_height *= ratio;
	} 
	
	if (new_height > max_height) {					
		var ratio = max_height / new_height;
		
		new_width *= ratio;
		new_height = max_height;	
	}
	
	return [Math.round(new_width), Math.round(new_height)];	
}
