/*
 * TIS scripts
 * @author developer
 */
function appendToContainerAsync(url, container, data){
    $.ajax({
        type: 'GET',
        data: data,
        url: url,
        cache: false,
        success: function(html){
            $(container).append(html);
        }
    });
}

function replaceContainerAsync(url, container, data, callback){
    var callback = callback ||
    function(){
    };
    $.ajax({
        type: 'GET',
        data: data,
        url: url,
        cache: false,
        success: function(html){
            $(container).empty();
            $(container).html(html);
            callback();
        }
    });
}

function ajax(params){
    $.ajax(params);
}

function showImagePopup(container, image, id){
    $.fn.image = function(src, f){
        return this.each(function(){
            var i = new Image();
            i.src = src;
            i.onload = f;
            this.appendChild(i);
        });
    }
    $(id).empty();
    $(id).image(image, function(){
    });

	showModal(container, 'big');

    return false;
}



var RouteList = {
    change: function(){
        window.setTimeout("RouteList.reload()", 1);
    },
    reload: function(){
        $("#route-list").html('<img src="' + env.IMG_loadingURL + '"/>');
        
        var sortBy = $("#route-search").linkselect("val");
        var objectId = $("#route-search-id").val();
        
        ajax({
            type: 'GET',
            data: {
                sortBy: sortBy,
                objectId: objectId
            },
            url: env.ROUTE_listURL,
            cache: false,
            success: function(data){
                $("#route-list").html(data);
            },
            error: function(data){
                $("#route-list").html('');
            }
        });
    }
};



function tooltip2(){
    $("a.internalCmsLink").each(function(e){
        var href = env.APP_ContextPath + $(this).attr("href");
        $(this).attr("href", href);
    });
    $("a.internalFileLink").each(function(e){
    	var href = env.APP_FileContextPath + $(this).attr("href");
    	$(this).attr("href", href);
    	$(this).attr("target", "_blank");
    });
    $("a.contact").each(function(){
        var id = $(this).attr("id");
        var href = $(this).attr("href");
        $('<div id="div' + id + '" class="tooltip ' + id + '"></div>').appendTo("body");
        replaceContainerAsync(env.CMS_tooltipURL, "#div" + id, {
            objectId: href
        }, function(){
            $("div.tooltip").find("p.close a").click(function(){
                $("div.tooltip").hide();
            });
            hoverImage();
        });
    });
    $("a.related").each(function(){
        var id = $(this).attr("id");
        $('<div id="div' + id + '" class="tooltip ' + id + '"></div>').appendTo("body");
    });
    $("a.contact, a.related").click(function(e){
        $("div.tooltip").hide();
        $("a.related").removeClass("related-active");
        var idname = $(this).attr("id");
        $("div." + (idname)).show().css("left", e.pageX - $("div." + (idname)).width() - 11 + "px").css("top", e.pageY - 79 + "px");
        if ($(this).hasClass("related")) {
            $(this).addClass("related-active");
            var href = $(this).attr("href");
            var rev = $(this).attr("rev");
            replaceContainerAsync(env.ROUTE_relatedObjectURL, "#div" + idname, {
                objectData: href,
                objectId: rev
            }, function(){
                $("div.tooltip").find("p.close a").click(function(){
                    $("div.tooltip").hide();
                    $("a.related").removeClass("related-active");
                });
            });
        }
        return false;
    });
}


var ShowObjectOnMap = {
    layerName: "objectLocationLayer",
    precision: 0.0001,
    initMultiple: function(coords, converter, clusterNear, clusterId) {
        //to cluster objects near to each other or not
        var clusterNear = (typeof clusterNear != 'undefined' && clusterNear) ? clusterNear : false;
        //check onlu points with same id
        var clusterId = (typeof clusterId != 'undefined' && clusterId) ? clusterId : false;
        var emptyfn = function(args){
            return args;
        };
        var converter = (typeof converter == 'function') ? converter : emptyfn;
        
        initMap(function(){
            Regio._Map.broadcastOnReady("layers.addSystemLayer", ShowObjectOnMap.layerName);
            var emouse = {
                pageX: 0,
                pageY: 0
            };
            $("#map-inner").mousemove(function(e){
                emouse.pageX = e.pageX;
                emouse.pageY = e.pageY;
            });
            var filtered = [];
            var count = coords.length;
            for (i = 0; i < count; i++) {
                if ((typeof coords[i].e == 'number' && typeof coords[i].n == 'number') ||
                (typeof coords[i].e == 'string' && typeof coords[i].n == 'string')) {
                    coords[i].serial = i;
                    filtered.push(coords[i]);
                }
                else 
                    if (typeof coords[i].e == 'object' && typeof coords[i].n == 'object') {
                    
                        for (var j = 0; j < coords[i].e.length; j++) {
                            var newObj = {
                                id: coords[i].id,
                                tooltip: coords[i].tooltip,
                                e: coords[i].e[j],
                                n: coords[i].n[j],
                                serial: i
                            };
                            filtered.push(newObj);
                        }
                    }
            }
            coords = filtered;
            count = coords.length;
            lest = []; //for expanding "too near" items
            for (i = 0; i < count; i++) {
                if (converter) {
                    coords[i] = converter(coords[i]);
                }
                coords[i].isDuplicate = false;
                coords[i].isNear = false;
                lest[i] = Regio.Coords.Convert(coords[i].e, coords[i].n, "WGS84", "LEST");
            }
            
            if (clusterNear) {
                //find "duplicates" = points that are very near to each other
                for (i = 0; i < count; i++) {
                    var point1 = coords[i];
                    for (j = 0; j < i; j++) {
                        var point2 = coords[j];
                        if (i == j) {
                            continue;
                        }
                        if (point1.e && point1.n && point2.e && point2.n) {
                            if (Math.abs(parseFloat(point1.e) - parseFloat(point2.e)) < ShowObjectOnMap.precision &&
                            Math.abs(parseFloat(point1.n) - parseFloat(point2.n)) < ShowObjectOnMap.precision) {
                                if ((clusterId && point.id != point2.id) || !clusterId) {
                                    coords[i].isDuplicate = true;
                                }
                            }
                        }
                    }
                }
            }
            
            var  drawPoints = function (count, coords) {
            	for (i = 0; i < count; i++) {
                    var point = coords[i];
                    if (point.e && point.n && !point.isDuplicate) {
                    	drawSinglePoint(i, point);
                    }
                }
            
            };
            var drawSinglePoint = function(i, point,  overloadCoords) {
            	var color = '008bcc';
            	var geo = {
                        e: point.e,
                        n: point.n
                    }
            	if(overloadCoords && overloadCoords.x && overloadCoords.y) {
            		geo = {
                            e: overloadCoords.x,
                            n: overloadCoords.y
                    };
            	}
                var label = point.serial + 1;
                var tooltip = (point.tooltip && point.tooltip.length > 1) ? point.tooltip : label + "";
                Regio._Map.broadcastOnReady("layers.addPointToSystemLayer", ShowObjectOnMap.layerName, {
                    objectId: i,
                    geo: [geo],
                    color: color,
                    symbolId: (label > 9) ? 'label2_' + (label) : 'label1_' + (label),
                    alpha: '80',
                    tooltip: tooltip
                });            	
            };
            drawPoints(count, coords);
            
            
            function installListeners(rec){
                var thatRec = rec;
				$(rec).each(function(){
					Regio._preloadToolTip(this.id);
				});
                Regio._Map.addCallback("objects.onClick", function(params){
                    if (thatRec[params.objectId] && thatRec[params.objectId].id) Regio._showToolTip(thatRec[params.objectId].id, emouse);
				 });
            }
            
            installListeners(coords);
          
            
            var distanceLest = function(point1, point2){
            	return Maht.sqrt((point1.e - point2.e)*(point1.e - point2.e) + (point1.n - point2.n)*(point1.n - point2.n));
            };
            
            var getBoundingBox = function(args) {
            	var max  = Regio.Coords.Convert(args.max_e, args.max_n, "WGS84", "LEST");
            	var min  = Regio.Coords.Convert(args.min_e, args.min_n, "WGS84", "LEST");
            	var bb = [min.e, min.n, max.e, max.n];
            	return bb;
            };
            
            var pixelMinDistance = 5;
            
            var size_x = $("#map-inner").width();
            var size_y = $("#map-inner").height();
            
            var lastZoom = -1;
            
           /*
            * Optimization: as interaction with map is slow, then with big number of markers, it gets very slow in total.
            * We can avaoid with some tricks interaction with flash component and cache position altough, but with marker numbers so big
            * it would not make sense, because we can not guarantee that we can still show all the markes. Instead, some neat maker clustering
            * should be considered.
            * 
            */
			if (coords.length <= 10) {
						
							Regio._Map.listeners.add("map.onMapParams", function(a){
								if (a && a.zoom != lastZoom) {
									var bbox = getBoundingBox(a);
									for (i = 0; i < count; i++) {
										var point = coords[i];
										if (point.e && point.n && !point.isDuplicate) {
											for (j = i + 1; j < count; j++) {
												var point2 = coords[j];
												if (i != j && point2.e && point2.n && !point2.isDuplicate) {
												
													//compare every other marker
													var xs = size_x / Math.abs(bbox[0] - bbox[2]); //pixel / m
													var ys = size_y / Math.abs(bbox[1] - bbox[3]); //pixel / m
													var dx = Math.abs(lest[i].e - lest[j].e) * xs; //distance on x axis in pixels
													var dy = Math.abs(lest[i].n - lest[j].n) * ys; //distance on y axis in pixels
													if (dx < pixelMinDistance || dy < pixelMinDistance) {
														var newGeo = Regio.Coords.Convert(lest[j].e + (pixelMinDistance / xs), lest[j].n + (pixelMinDistance / ys), "LEST", "WGS84");
														drawSinglePoint(j, point2, newGeo);
													} else {
														drawSinglePoint(j, point2);
													}
													
												}
											}
										}
									}
									
									
								}
								if (a) {
									lastZoom = a.zoom;
								}
								
							});
						}
			
            
        });
        
    }
};


function drawRasterMap(defaultPoints, jqueryContainer){
    var objectId = objectId || false;
	var i = new Image();
	var e = "";
	var n = "";
    var firstRun = true;
    $(defaultPoints).each(function(){
        if (this.e && this.n) {
            if (!firstRun) {
                e = e + ",";
                n = n + ",";
            }
            e = e + this.e;
            n = n + this.n;
            firstRun = false;
        }
    });
    if (e != "" || n != "") {
    	i.src = env.MAP_imageNoCacheURL + "?e=" + e + "&n=" + n;
	    jqueryContainer.empty();
	    jqueryContainer.append(i);
    }
}

function addMapIcons() {
	$("div.map-hidden-data").find("p.map-ico").each(
		function () {
			var link = $(this).find("a");
			link.find(".imgBig").hide();
			link.hover(
				function () {
					$(this).find(".imgSmall").hide();
					$(this).find(".imgBig").show();
				}, 
				function () {
					$(this).find(".imgBig").hide();
					$(this).find(".imgSmall").show();
				}
			);
			$("div.map-small-inner").append($(this))
		}
	);
	$("div.map-hidden-data").show();
}

$(document).ready(function(){
	if ($.browser.msie) {
		var replaceTile = function() {
			document.title = env.APP_title;
		};
		$(window).bind('load', replaceTile);
	}
	SendMailPopup.init("#sendForm");
});

var SendMailPopup = {
	init : function(popupId) {
		var _this = this;
		$("p.action input", popupId).click(function() {
			_this.send(popupId);
		});
	},
	clear: function(popupId) {
		$("div.message", popupId).hide();
		$("p.mailsent", popupId).hide();
		$("p.pclose", popupId).hide();
		$("table.form input, table.form textarea", popupId).each(function() {
			$(this).val("");
		});
		$("table.form td", popupId).each(function() {
			$(this).removeClass("error");
		});
		$("p.action", popupId).show();
		$("table.form", popupId).show();
		return false;
	},
	fade: function(popupId, mainDiv) {
		var _this = this;
		$(mainDiv).pause(3000).fadeOut(150, function() {
			$("#overlay").css("display","none");
			_this.clear(popupId);
		});
	},
	send: function(popupId) {
		$("p.action", popupId).html('<img src="' + env.IMG_loadingURL + '"/>');
		var data = new Object();
		data.save = true;
		data.requestUrl = document.location.href;
		$("table.form input, table.form textarea", popupId).each(function() {
			data[$(this).attr("name")] = $(this).val();
		});
		ajax({
			type: 'GET',
			data: data,
			url: env.MAIL_sendURL,
			cache: false,
			success: function(data) {
				$(popupId).html(data);
			},
			error: function(data) {
				$(popupId).html('Error!!!');
			}
		});
	}
};

function showPopup(target, divId, size) {
	divId = "#" + divId;
	if ($("#overlay").length == 0) {
		$("#wrap").after("<div id='overlay'></div>");
	}
	if (openModalContent != null){
		$("#" + openModalContent).hide();
	}
	openModalContent = target;

	$("#overlay").css("display","block");
	$("#" + target).css("display","block");
	$(divId).fadeIn(150);

	if(size == 'big'){
		$(divId).addClass("modalpopup-large");
		$(divId).removeClass("modalpopup-small");
		$(divId).removeClass("modalpopup-normal");
	} else if(size == 'small'){
		$(divId).addClass("modalpopup-small");
		$(divId).removeClass("modalpopup-normal");
		$(divId).removeClass("modalpopup-large");
	} else {
		$(divId).addClass("modalpopup-normal");
		$(divId).removeClass("modalpopup-small");
		$(divId).removeClass("modalpopup-large");
	}

	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		$("html").css("overflow","hidden");
		if($("div.modalpopup-content").height() > "400") {
			$("div.modalpopup-content").css("height","400");
		}
	} else {
		$(divId).css("margin-top","-" + $(divId).height() / 2 + "px");
	}

	$("#overlay").bgiframe({ src: "javascript:'<html></html>';" });

	escape();
	return false;
}

function hidePopup(divId){
	divId = "#" + divId;
	if (openModalContent != null){
		$("#" + openModalContent).fadeOut(150);
	}
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("html").css("overflow","");
	}
	$(divId).fadeOut(150, function(){
		$("#overlay").css("display","none");
	});
	return false;
}