var GlobalSettings={"lang":"hr"};
// TODO u posebnu JSON varijablu stavi slike npr Icons, au posebnu Backgrounds i Images
// TODO ovo stavi u JS file koji će se dati mijenjati


var Templates;
function ShowCurrentEvents() {
    for (var key in Templates) {
        if (typeof(Templates[key].level)=="undefined") {    // znaci da su nivo 1
            if (typeof(Templates[key].visible)!="undefined" && typeof(Templates[key].startTime)!="undefined" ) {
                if (Templates[key].visible=='y') {
                    var timer=setTimeout("homePageEvents(Templates['"+key+"']);",Templates[key].startTime);
                    Timers[key]=timer;
                }
            }
        } else if (Templates[key].level==2) {    // znaci da su nivo 2
            if (typeof(Templates[key].visible)!="undefined") {
                if (Templates[key].visible=='y') {
                    homePageEventsLevel2(Templates[key],key);
                }
            }
        }
    }
}


var Timers={};

function ClearTimer(timerKey) {
    var timer=Timers[timerKey];
    clearTimeout(timer);
    delete Timers[timerKey];
}

function ClearAllTimers() {
    for (var key in Timers)
    {
        ClearTimer(key);
    }
}

// TODO: podesi selectLocationsInProgress
// TODO: dodaj machine direktno ko listu u opis svakog kluba

var pic0=new Image(200,72);pic0.src='imgs/logo_g_no_bg_200_72_2.png';
var pic1=new Image(100,100);pic1.src="icons/dice_70_70_sh.png";
var pic2=new Image(99,91);pic2.src="icons/cro_small2_sh.png";
var pic3=new Image(55,100);pic3.src="icons/apex_st2_25_70_sh.png";
var pic4=new Image(90,90);pic4.src="icons/rull2_small2_sh.png";
var pic5=new Image(87,86);pic5.src="icons/logo_small2_rot_sh.png";
var pic6=new Image(180,234);pic6.src="imgs3/herz_as_sg_r10_sh.png";
var pic7=new Image(180,234);pic7.src="imgs3/karo_as_sg_r10_sh.png";

var pic8=new Image(16,16);pic8.src="icons/xr.gif";
var pic9=new Image(16,16);pic9.src="icons/xra.gif";
var pic10=new Image(16,16);pic10.src="icons/play_left2r.png";
var pic11=new Image(16,16);pic11.src="icons/play_left2ra.png";
var pic12=new Image(30,15);pic12.src="icons/bhrv.gif";
var pic13=new Image(30,15);pic13.src="icons/beng.gif";
var pic14=new Image(30,15);pic14.src="icons/bhrv_g.gif";
var pic15=new Image(30,15);pic15.src="icons/beng_g.gif";

var pic16=new Image(140,16);pic16.src="imgs/bg_menu3rb16.png";
var pic17=new Image(16,16);pic17.src="icons/xg.gif";
var pic18=new Image(16,16);pic18.src="icons/xga.gif";

var pic19=new Image(530,410);pic19.src="imgs/bg_red_gogs_500_380_op90_6.png";

var pic20=new Image(830,510);pic20.src="imgs/bg_830_510_blue3_bev_sh.png";

var pic21=new Image(130,130);pic21.src="imgs/smokeallowed2.png";
var pic22=new Image(530, 410);pic22.sec="imgs/bg_red_gogs_500_380_op90_7.png";

var lang='hr';

/**** STAT ****/
function ksStat(name) {
	this.name=name;
}
ksStat.prototype.write=function(page,url) {
    var tsTimeStamp= new Date().getTime();
    var params={action: "get", time: tsTimeStamp};
    params['page']=page;
    params['url']=page;
    var tableUrl='dataRetrival/setSttAccessedPage.php';	
	$.get(tableUrl, params, function(data){
		//alert(data);
		//alert(data.ip);
		//alert(data.host);
	});
}
var gogsStat=new ksStat("gogsStat");
/**************/

/*********** ALBUM ************/
function ksAlbum(name, origSize, onClose) {
    this.thumbList=new Array();
    this.imageList=new Array();
    this.currentIndex="0";
    this.thumbListRight=false;
    this.thumbListLeft=false;
    this.thumbListCreated=false;
    this.thumbListViewWidth=0;
    this.albumName=name;
    this.parentNodeId=null;
    this.origSize=false;
    if (typeof(onClose)!='undefined') {
        this.onClose=onClose+";";
    }
    if (typeof(origSize)!='undefined') {
        this.origSize=origSize;
    }

}

ksAlbum.prototype.hoverEfectLRIn=function(ev, el) {
    var backImg=$(el).css("background-image");
    var newBackImage=backImg.replace(".png","_hv.png");
    $(el).css("background-image", newBackImage);
    $(el).css("cursor","pointer");
    stopPropagate(ev);
}

ksAlbum.prototype.hoverEfectLROut=function(ev, el) {
    var backImg=$(el).css("background-image");
    var newBackImage=backImg.replace("_hv.png",".png");
    $(el).css("background-image", newBackImage);
    $(el).css("cursor","normal");
    stopPropagate(ev);
}

ksAlbum.prototype.hoverEfectLRIn2=function(ev, el) {
    var img=$(el).attr("src");
    var newImage=img.replace(".gif","a.gif");
    newImage=newImage.replace(".png","a.png");
    $(el).attr("src", newImage);
    $(el).css("cursor","pointer");
    stopPropagate(ev);
}

ksAlbum.prototype.hoverEfectLROut2=function(ev, el) {
    var img=$(el).attr("src");
    var newImage=img.replace("a.gif",".gif");
    newImage=newImage.replace("a.png",".png");
    $(el).attr("src", newImage);
    $(el).css("cursor","normal");
    stopPropagate(ev);
}

ksAlbum.prototype.iteratorAddThumb=function (left, index) {
    if (index < this.thumbList.length) {
        var album=this;
        var image=new Image();
        image.src=this.thumbList[index];
        $(image).load(function() {
            $("<img class='thumbAlbum' style='position:absolute;top:0px;left:"+left+"px;' src='"+album.thumbList[index]+"' id='"+album.albumName+"_"+index+"'   onclick='"+album.albumName+".thumbSelect(event, this,"+index+",\"#div0\")'/>").appendTo("#"+album.albumName+"_thumbList");
            left+=parseInt($(this).attr("width"));
            index++;
            album.thumbListViewWidth=left;
            album.iteratorAddThumb(left,index);
        });
    }
}

ksAlbum.prototype.fillThumbList=function () {
    this.iteratorAddThumb(0,0);
}

ksAlbum.prototype.thumbsLeft=function (ev) {  // TODO: zakodirana širina thumb sličica	
    $("#"+this.albumName+"_thumbList").stop(true,true);
    var left=parseInt($("#"+this.albumName+"_thumbList").css("left"));
    var rightEnd=parseInt($("#"+this.albumName+"_thumbList_wrapper").css("width"));
    if (left<0) {
        $("#"+this.albumName+"_thumbList").animate({left:(left+100)+"px"},800);
    }
    stopPropagate(ev);
}

ksAlbum.prototype.thumbsRight=function (ev) {
    $("#"+this.albumName+"_thumbList").stop(true,true);
    var left=parseInt($("#"+this.albumName+"_thumbList").css("left"));
    var rightEnd=parseInt($("#"+this.albumName+"_thumbList_wrapper").css("width"));

    if (left<=0 && left+this.thumbListViewWidth>rightEnd) {
        $("#"+this.albumName+"_thumbList").animate({left:(left-100)+"px"},800);
    }
    stopPropagate(ev);
}

ksAlbum.prototype.thumbSelect=function (ev, el, index, parentFilter, addFunctionOnClose) {
    var newSrc=this.imageList[index];
    var currentSelected="#selectedThumb_"+this.albumName+"_"+this.currentIndex;
    var newSelected     ="selectedThumb_"+this.albumName+"_"+index;
    var albumName=this.albumName;
    var origSize=this.origSize;
    //
    var wid=200;
    var hei=433;
    var dwid=wid+4+"px";
    var dhei=hei+4+"px";
    var top="-"+(hei+27)+"px";
    var left=((500-wid/2)-2)+"px";
    var leftLeft=(wid-37)+"px";
    var leftClose=(wid-17)+"px";
    //
    var count=this.imageList.length;
    var onClose=this.onClose;
    var img=new Image();
    img.src=newSrc;
    $(currentSelected).animate({top:"600px"},800, function(){$(currentSelected).remove();});

    var selected="<div id='"+newSelected+"' class='album' style='position:absolute; z-index:2000; background-color:white; color:black; top:"+top+"; left:"+left+"; width:"+dwid+";height:"+dhei+";'>\n\
       </div>";
//alert(newSelected);
    $(selected).appendTo(parentFilter);   //appendTo("#show1");" +
    $("#"+newSelected).css({opacity: 0.5});
//alert(selected);
//alert(newSelected);
    dropFromAbove("#"+newSelected,parseInt(top),20);
    //$("#img_"+newSelected).fadeIn(2000);
    $(img).load(function() {
        if (origSize) {
            wid=$(this).attr("width");
            hei=$(this).attr("height");
        } else {
            wid=800;
            hei=533;
        }
        dwid=wid+4+"px";
        dhei=hei+4+"px";
        //top="-"+(hei+27)+"px";
        left=((500-wid/2)-2)+"px";
        leftLeft=(wid-37)+"px";
        leftClose=(wid-17)+"px";
        var selectedImg="<img id='img_"+newSelected+"' src='"+newSrc+"' style='display:none;position:absolute;margin: 2px;' width="+wid+" height="+hei+" />";
        if (index>0) {
            selectedImg=selectedImg+"<img src='icons/play_left2r.png' style='position:absolute; top:5px; left:5px;' onclick='"+ albumName+".playLeft(event)' \n\
                onmouseout='"+albumName+".hoverEfectLROut2(event, this)'\n\
                onmouseover='"+albumName+".hoverEfectLRIn2(event, this)'\n\
            />";
        }
        if (index<count-1) {
            selectedImg=selectedImg+"<img id='r_"+newSelected+"' src='icons/play2r.png' style='position:absolute; top:5px; left:"+leftLeft+";' onclick='"+ albumName+".playRight(event)'\n\
                onmouseout='"+albumName+".hoverEfectLROut2(event, this)'\n\
                onmouseover='"+albumName+".hoverEfectLRIn2(event, this)'\n\
            />";
        }
        selectedImg=selectedImg+"<img id='x_"+newSelected+"'  src='icons/xr.png' style='position:absolute; top:5px; left:"+leftClose+";' onclick='"+ albumName+".closeAlbum(event);"+onClose+"'\n\
                onmouseout='"+albumName+".hoverEfectLROut2(event, this)'\n\
                onmouseover='"+albumName+".hoverEfectLRIn2(event, this)'\n\
            />";
        $("#"+newSelected).animate({left:left, width:dwid, height:dhei},500,null,function(){
            $(this).append(selectedImg);
            $("#img_"+newSelected).fadeIn(100);
            $("#"+newSelected).animate({opacity:1}, 200);
        });

    });

    this.currentIndex=index;
    stopPropagate(ev);
}

ksAlbum.prototype.playLeft=function(ev) {
    var index;
    if (this.currentIndex>0) {
        index=this.currentIndex-1;
    }else {
        stopPropagate(ev);
        return;
    }
    var el=$("#"+this.albumName+"_"+index).get(0);
    this.thumbSelect(ev,el,index,"#div0");
}

ksAlbum.prototype.playRight=function(ev) {
    var index;
    if (this.currentIndex<this.imageList.length-1){
        index=this.currentIndex+1;
    } else {
        stopPropagate(ev);
        return;
    }
    var el=$("#"+this.albumName+"_"+index).get(0);
    this.thumbSelect(ev,el,index,"#div0");
}

ksAlbum.prototype.closeSelected=function(ev,el) {
    $(el).remove();
    stopPropagate(ev);
}
ksAlbum.prototype.closeAlbum=function(ev) {
    // $("#albumShadow").remove();
    $("#selectedThumb_"+this.albumName+"_"+this.currentIndex).animate({top:"1100px"}, 1000,null, function(){$("#selectedThumb"+this.currentIndex).remove();});
    stopPropagate(ev);
}

ksAlbum.prototype.showThumbs=function(ev, parentFilter, top, left, width, height, thumbWidth, title) {
	var widthR=width+4;
	var heightR=height+4;
	var deltaHeight=0;
	if (title) {
		deltaHeight=14;
	};
	if (checkElements("#"+this.albumName+"_thumbs")) {
		$("#"+this.albumName+"_thumbs").remove();
	}
		
	var thumbs="<div id='"+this.albumName+"_thumbs' style='display: none;background:white;position:absolute;left:"+left+"px;top:"+top+"px;width:"+(width+4)+"px;height:"+(height+4+deltaHeight)+"px;z-index:70;'>";
	if (title) {
		thumbs=thumbs+"<div style='position:absolute;left:5px;top:0px;width:80px;color:black;'>Foto album</div>"
	}
    thumbs=thumbs+"     <div id='"+this.albumName+"_wrapper' style='position:absolute;top:"+(2+deltaHeight)+"px;left:2px;width:"+(width+2)+"px;height:"+height+"px;'>"+
       "     <div id='"+this.albumName+"_naviLeft' onmouseover='"+this.albumName+".hoverEfectLRIn(event, this)' onmouseout='"+this.albumName+".hoverEfectLROut(event, this)' "+
       "     onclick='"+this.albumName+".thumbsLeft(event)' style='position:absolute;left:0px;width:10px;height:"+height+"px;background-color:gray;"+
       "     background-image:url(icons/album_left2.png); '/> "+
       "     <div id='"+this.albumName+"_thumbList_wrapper' style='left:10px;position:absolute; overflow:hidden;height:100px;width:"+(width-20)+"px;'> "+
       "         <div id='"+this.albumName+"_thumbList' style='position:absolute;width:3000px;left:0px;'> " +
       "         </div> "+
       "     </div>"+
       "     <div id='"+this.albumName+"_naviRight' onmouseover='"+this.albumName+".hoverEfectLRIn(event, this)' "+
       "     onmouseout='"+this.albumName+".hoverEfectLROut(event, this)'  onclick='"+this.albumName+".thumbsRight(event)' "+
       "     style='position:absolute;left:"+(width-10)+"px;width:10px;height:"+height+"px;background-color:gray;background-image:url(icons/album_right2.png)'/> "+
       " </div>"+
       "</div>";
    //alert(thumbs);
    $(thumbs).appendTo(parentFilter);
    $("#"+this.albumName+"_thumbs").fadeIn(2000);
}

ksAlbum.prototype.showAlbum=function(ev) {
//alert(albumName+" uuu");
//    $("<div id='album' style='width:1000px;height:640px;position:absolute;top:0px;left:0px;z-index:7000;'></div>").appendTo("#show1");
    $("<div id='"+this.albumName+"' style='background:white;position:absolute;left:100px;top:-670px;width:804px;height:638px;z-index:7000;'>\n\
            <div id='"+this.albumName+"_wrapper' style='position:absolute;top:2px;left:2px;width:802px;height:100px;'>\n\
                <div id='"+this.albumName+"_naviLeft' onmouseover='"+this.albumName+".hoverEfectLRIn(event, this)' onmouseout='"+this.albumName+".hoverEfectLROut(event, this)'\n\
                onclick='"+this.albumName+".thumbsLeft(event)' style='position:absolute;width:10px;height:100px;background-color:gray;\n\
                background-image:url(icons/album_left2.png); '/>\n\
                <div id='"+this.albumName+"_thumbList_wrapper' style='left:10px;position:absolute; overflow:hidden;height:100px;width:780px;'>\n\
                    <div id='"+this.albumName+"_thumbList' style='position:absolute;width:3000px;height:300px;left:0px;'>\n\
                    </div>\n\
                </div>\n\
                <div id='"+this.albumName+"_naviRight' onmouseover='"+this.albumName+".hoverEfectLRIn(event, this)'\n\
                onmouseout='"+this.albumName+".hoverEfectLROut(event, this)'  onclick='"+this.albumName+".thumbsRight(event)'\n\
                style='position:absolute;left:790px;width:10px;height:100px;background-color:gray;background-image:url(icons/album_right2.png)'/>\n\
            </div>\n\
            <div id='"+this.albumName+"_selectedImage' style='position:absolute;left:0px;top:100px;width:800px;height:540px;'>\n\
            </div>\n\
        </div>").appendTo("#show1");
    this.fillThumbList();
    var el=$("#"+this.albumName+"_0").get(0);
    this.thumbSelect(ev,el);
    var elAlbum=$("#"+this.albumName).get(0);
    $("#"+this.albumName).animate({top:"0px"}, 1000,null, function(){shadowElement(elAlbum, false, 0, "albumShadow");});
    stopPropagate(ev);
}


ksAlbum.prototype.thumbsRightCont=function () {
    var left=$("#thumbList").css("left");
    left=parseInt(left);
    left=left-50;
    $("#thumbList").animate(
        {left:left},
         3000 ,
         "",
         function() {album.thumbsRightCont();}
    );
}




function eIg(ev) {
    var el;
    if (ev.target) {
        el=ev.target;
        ev.stopPropagation();
    } else if(ev.srcElement) {
        el=ev.srcElement;
        ev.cancelBubble=true;
    }

   $(el).css("height", "200px");
   $(el).css("width", "300px");
   newImg=document.createElement("IMG");
   newImg.src=el.src;
   //el.parentNode.replaceChild(newImg, el);
}

function moIg(ev) {
    var el;
    if (ev.target) {
        el=ev.target;
        ev.stopPropagation();
    } else if(ev.srcElement) {
        el=ev.srcElement;
        ev.cancelBubble=true;
    }
   $(el).css("height", "70px");
   $(el).css("width", "110px");
   /*
    $(el).animate(
        { width:"110px", height:"70px" },
        { queue:false, duration:300 }
    )
    */
}

// constructor for point
function ksPoint(x, y) {
	this.x=x;
	this.y=y;
}
var mousePos=new ksPoint(0,0);
var oldMousePos=new ksPoint(0,0);
function ksMousePosition(e) {
	mousePos.x = 0;
	mousePos.x = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		mousePos.x = e.pageX;
		mousePos.y = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		mousePos.x = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		mousePos.y = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
}
/*********** ALBUM ************/


/************** SMCITEM **************/
function SmcItem(num, name, name2, description) {
	this.num=num;
	this.name=name;
	this.name2=name2;
	this.description=description;
}

function SmcItems(location,dataUrl, params) {
	this.location=location;
	this.loaded=false;
	this.dataUrl=dataUrl;
	this.params=params;
	this.list=new Array();	
}

SmcItems.prototype.get=function(index) {
	return this.list[index];
}

SmcItems.prototype.length=function() {
	return this.list.length;
}

SmcItems.prototype.set=function(index, smcItem) {
	this.list[index]=smcItem;
}

SmcItems.prototype.add=function(smcItem) {
	this.list[this.list.length]=smcItem;
}

SmcItems.prototype.listItems=function(ev, parentFilter, cols, rows, all, top, left){
	var colWidth=140;
	var menuItem="";
	var currCol=0;
	var j=0;
	var cols=new Array();
	var top2=top+30;
	$("<div class='machinesList' style='position:absolute;top:"+top+"px;left:"+left+"px;'><h4>"+langResources['availableMachines']+"</h4></div>").appendTo(parentFilter);
	cols[0]="<div class='machinesList' style='position:absolute;top:"+top2+"px;left:"+left+"px;'>";
	if (all) {
		var len=gogsMachines.length();
		for (var i=0;i<len;i++) {
			if (j==rows) {
				j=0;
				cols[currCol]=cols[currCol]+"</div>";
				currCol++;
				cols[currCol]="<div class='machinesList' style='position:absolute;top:"+top2+"px;left:"+(left+currCol*colWidth)+"px;'>";
			} 
			menuItem="<div class='menu4' style='font-size: 11px;width:"+colWidth+"px;' onclick='alert(\" about machine\")'>"+ gogsMachines.get(i).name2 +"</div>";
			cols[currCol]=cols[currCol]+menuItem;	
			j++;
		}
	} else {	
		var len=currentLocation.machines.length();
		for (var i=0;i<len;i++) {
			if (j==rows) {
				j=0;
				cols[currCol]=cols[currCol]+"</div>";
				currCol++;
				cols[currCol]="<div class='machinesList' style='position:absolute;top:"+top2+"px;left:"+(left+currCol*colWidth)+"px;'>";
			} 	
			menuItem="<div class='menu4' style='width:"+colWidth+"px;' onclick='showDisplayDesc(\""+currentLocation.machines.get(i).num+"\")'>"+ currentLocation.machines.get(i).name2 +"</div>";
			cols[currCol]=cols[currCol]+menuItem;					
			j++;
		}
	}
	cols[currCol]=cols[currCol]+"</div>";
	for (var i=0;i<=currCol;i++) {
		//alert(cols[i]);
		$(cols[i]).appendTo(parentFilter);
	}
	$("div.menu4").bind("mouseout",function(){hoverDivBgImgOut(this);});
	$("div.menu4").bind("mouseover", function() {hoverDivBgImgIn(this, 'imgs/bg_menu3rb16.png');})
}

SmcItems.prototype.load=function(smcItems) {
    var tsTimeStamp= new Date().getTime();
    var params={action: "get", time: tsTimeStamp};
    if (smcItems.params == null) {
    } else {
    	// params=params.appned(smcItems.params);
    	for (var key in smcItems.params) {
    		params[key]=smcItems.params[key];
    		//alert(key+" "+params[key]);
    	}
    }
    var tableUrl=smcItems.dataUrl;	
	if (smcItems.loaded) {
		smcItems.list.length=0;
	}
	$.get(tableUrl, params, function(data){
    	var table=jQuery(data, document);
    	var rows=$(table).find("tr");
    	var len=rows.length;
    	for (var i=0;i<len;i++) {
    		var cells=$(rows.get(i)).find("td");
    		var num=$(cells.get(0)).text();
    		var name=$(cells.get(1)).text();
    		var name2=$(cells.get(2)).text();
    		var description=$(cells.get(3)).html();
    		smcItems.add(new SmcItem(num,name, name2, description));
    	}
    	table.remove();
    	smcItems.loaded=true;		
	});
}
/************** SMCITEM **************/



/*  Common functions */
function stopPropagate(ev) {
    if (jQuery.isFunction(ev.stopPropagation)) {
        ev.stopPropagation();
    } else {
        ev.cancelBubble=true;
    }
}

function checkElements(filter) {
	if ($(filter).length>0) {
		return true;
	}else {
		return false;
	}
}

function pausecomp(millis) 
{
	var date = new Date();
	var curDate = null;
	
	do {curDate = new Date();} 
	while(curDate-date < millis);
}

var langResources;
var loadLangResInprogress=false;
loadLanguageResources('#div0', 'hr');
function loadLanguageResources(element, lang1) {
	// it has to be executetd in html head!!!	
	var params={action: "get", language: lang1};	
	loadLangResInprogress=true;
	$.getJSON("resources/getLanguageResource.php", params, function(data) {
		langResources=data;
		makeLanguageChanges(element);
		loadLangResInprogress=false;
	});
	//while (loadLangResInprogress) {
	//	pausecomp(20);
	//}
}

function changeLanguage(element, lang1) {
	/*
	if (whereWasI.currPlaceIs()!=whereWasI.home) {
		return;		
	}
	*/
	//TODO: sakrij sve menije (ako postoje) i sakrji display ako postoji i prikaži ga ponovo
	//if (whereWasI.currPlaceIs()=='location') {   //20100506
	//	closeLocation();
	//}
	if (lang!=lang1) {
		lang=lang1;
		loadLanguageResources(element, lang1);
	}
	whereWasI.lastFunctionCall();
	// selectLocation(currentLocation.code, currentParentLocation); //20100506
}
function makeLanguageChanges(element) {
	ths=$(element).find("th[translateAs]");
	len=ths.length;
	for (i=0;i<len;i++) {
		newText=langResources[$(ths[i]).attr("translateAs")];
		$(ths[i]).text(newText);
	}
	ps=$(element).find("p[translateAs]");
	len=ps.length;
	for (i=0;i<len;i++) {
		//alert($(ps[i]).attr("translateAs"));
		newText=langResources[$(ps[i]).attr("translateAs")];
		$(ps[i]).text(newText);
	}
	divs=$(element).find("div[translateAs]");
	len=divs.length;
	for (i=0;i<len;i++) {
		//alert($(ps[i]).attr("translateAs"));
		newText=langResources[$(divs).attr("translateAs")];
		$(divs[i]).text(newText);
	}	
}

function hoverDivBgImgIn(el, imgName) {
	$(el).css("background","transparet url("+imgName+") no-repeat left top");
}

function hoverDivBgImgOut(el) {
	$(el).css("background","");
}
/* End Comon Functions */

/* MAIN GLOBALS for page and sub page manipulating*/
function functionCall(calledFunction, param1, param2, param3, parma4, param5) {
	this.calledFunction=calledFunction;
	if (typeof(param1)!='undefined') this.param1=param1;
	if (typeof(param2)!='undefined') this.param2=param2;
	if (typeof(param3)!='undefined') this.param3=param3;
	if (typeof(param4)!='undefined') this.param4=param4;
	if (typeof(param5)!='undefined') this.param5=param5;
}

function WhereWasI(name,home) {
	this.name=name;
	this.stack=new Array();
	this.home=home;
	this.functionStack=new Array();
	if (home!=null) {
		this.stack.push(home);
	}
}

WhereWasI.prototype.goToNewPlace=function(placeName, calledFunction, param1, param2, param3,param4, param5) {
	this.stack.push(placeName);
	if (typeof(calledFunction)!='undefined') {
		var fc=new functionCall(calledFunction, param1, param2, param3,param4, param5);
		this.functionStack.push(fc);
	} else {
		var fc=new functionCall(null, null, null, null, null, null);
		this.functionStack.push(fc);
	}
	/*
	$("#imgEng").attr("src","icons/beng_g.gif");
	$("#imgHrv").attr("src","icons/bhrv_g.gif");
	$("#imgEng").attr("class","");
	$("#imgHrv").attr("class","");
	*/
}

//WhereWasI.prototype.goToNewPlace=function(placeName) {
//	this.stack.push(placeName);
	/*
	$("#imgEng").attr("src","icons/beng_g.gif");
	$("#imgHrv").attr("src","icons/bhrv_g.gif");
	$("#imgEng").attr("class","");
	$("#imgHrv").attr("class","");
	*/
//}
WhereWasI.prototype.lastFunctionCall=function() {
	var fc=this.functionStack[this.functionStack.length-1];
	var lastFunction=fc.calledFunction;
	if (lastFunction!=null) {
		var param1=fc.param1;
		var param2=fc.param2;
		var param3=fc.param3;
		var param4=fc.param4;
		var param5=fc.param5;
		if (typeof(param1)=='undefined') {		
			lastFunction();
		} else if (typeof(param2)=='undefined') {		
			lastFunction(param1);
		} else if (typeof(param3)=='undefined') {		
			lastFunction(param1,param2);
		} else if (typeof(param4)=='undefined') {		
			lastFunction(param1,param2,param3);
		} else if (typeof(param5)=='undefined') {		
			lastFunction(param1,param2,param3,param4);
		} else  {		
			lastFunction(param1,param2,param3,param4,param5);
		} 
	}
}

WhereWasI.prototype.returnToPrevPlace=function() {
	if (this.stack.length>1) {
		this.stack.pop();
		this.functionStack.pop();
		return this.stack[this.stack.length-1];
	}
	return null;
}

WhereWasI.prototype.currPlaceIs=function() {
	if (this.stack.length>0) {
		return this.stack[this.stack.length-1];
	} else {
		return null;
	}
}

WhereWasI.prototype.prevPlaceIs=function() {
	if (this.stack.length>1) {
		return this.stack[this.stack.length-2];
	} else {
		return null;
	}
}

WhereWasI.prototype.goHome=function() {
	this.stack.lenght=0;
	if (this.home!=null) {
		this.stack.push(this.home);
	}
	$("#imgEng").attr("src","icons/beng.gif");
	$("#imgHrv").attr("src","icons/bhrv.gif");
	$("#imgEng").attr("class","langImg");
	$("#imgHrv").attr("class","langImg");	
}

WhereWasI.prototype.getPath=function(type) {
	// TODO: da li to uopće trebam
	if (type='likeFolders') {
	} else if (type='likeFolders') {
	}
}

whereWasI=new WhereWasI('Gogs','home');
/* MAIN GLOBALS for page and sub page manipulating*/


/****************/
/*              */
/* GMAPS        */
/*	            */
/****************/

function GMapLocation(name, code, lat, lon) {
    this.subLocations=new Array();
    this.parentLocation=null;
    this.lat=lat;
    this.lon=lon;
    this.zoom=12; // default value
    this.name=name;
    this.secondName="";
    this.code=code;    
    this.street="";
    this.thumb="dice_70_70_sh.png";
    this.marker=null;
    this.info="";
    this.city="";
    this.description="";	
    this.subLoaded=false
    this.machines=new SmcItems(this,"dataRetrival/getMachinesByClub.php", {num2:code});
}

function GMapLocations(name) {
    this.locations=new Array();
    this.name=name;
}
GMapLocations.prototype.allLocationsLoaded=function() {
    var ret=true;
	var len=this.locations.length;
    for (i=0;i<len;i++) {
    	if (!this.locations[i].subLoaded) {
    		ret=false;
    		break;
    	}
    }
    return ret;
}

GMapLocations.prototype.findByCode=function(code) {
    var ret=null;
	var len=this.locations.length;
    for (i=0;i<len;i++) {
    	if (this.locations[i].code==code) {
    		ret=this.locations[i];
    		break;
    	}
    }
    return ret;
}
GMapLocations.prototype.findByLatLon=function(lat, lon) {
    var ret=null;
	var len=this.locations.length;
    for (i=0;i<len;i++) {
    	if (this.locations[i].lat==lat && this.locations[i].lon==lon) {
    		ret=this.locations[i];
    		break;
    	}
    }
    return ret;
}

GMapLocations.prototype.findSubByLatLon=function(lat, lon) {
    var ret=null;
	var len=this.locations.length;
    for (var i=0;i<len;i++) {
    	var len2=this.locations[i].subLocations.length;
    	for (var j=0;j<len2; j++) {
	    	if (this.locations[i].subLocations[j].lat==lat && this.locations[i].subLocations[j].lon==lon) {
	    		ret=this.locations[i].subLocations[j];
	    		break;
	    	}
    	}
    	if (ret!=null) {
    		break;
    	}
    }
    return ret;
}

GMapLocations.prototype.findSubByCode=function(code) {
    var ret=null;
	var len=this.locations.length;
    for (var i=0;i<len;i++) {
    	var len2=this.locations[i].subLocations.length;
    	for (var j=0;j<len2; j++) {
	    	if (this.locations[i].subLocations[j].code==code) {
	    		ret=this.locations[i].subLocations[j];
	    		break;
	    	}
    	}
    	if (ret!=null) {
    		break;
    	}
    }
    return ret;
}

var gogsLoc=new GMapLocations('Gogs');
var gogsMachines=new SmcItems(null,"dataRetrival/getMachines.php", null);
gogsMachines.load(gogsMachines);

var gMap;
var currentCity=new GMapLocation("none","non",null,null);
var currentLocation=null;
var currentParentLocation=null; //  20100506
var markers=new Array();
function onLoadMaps(cityCode)
		 {	
			 if (GBrowserIsCompatible())
			 {
				 gMap = new GMap2(document.getElementById("gmap_canvas"));
				 var loc=gogsLoc.findByCode(cityCode);		 
				 gMap.setCenter(new GLatLng(loc.lat, loc.lon), parseInt(loc.zoom));
				 gMap.setUIToDefault();
                 var iconGogs=new GIcon();
                 iconGogs.image =	 "http://www.gogs.hr/icons/logo_red_bg_ext2_arr_50_23.png";
                 iconGogs.shadow =	 "http://www.gogs.hr/icons/logo_red_bg_ext2_arr_50_23_sh.png";
                 iconGogs.iconSize = new GSize(50, 23);
                 iconGogs.shadowSize = new GSize(60, 33);
                 iconGogs.iconAnchor = new GPoint(1, 23);
                 iconGogs.infoWindowAnchor = new GPoint(23, 1);
                 currentCity=loc;
                 var k=0;
                 var len=gogsLoc.locations.length;
                 for (var i=0;i<len;i++) {
                	 var len2=gogsLoc.locations[i].subLocations.length;
                	 for (var j=0;j<len2;j++) {
		                 var point = new GLatLng(gogsLoc.locations[i].subLocations[j].lat, gogsLoc.locations[i].subLocations[j].lon);
		                 markers[k]=new GMarker(point,{icon:iconGogs});
		                 GEvent.addListener(markers[k], "click", function(latLang) {    
		                	 var loc=gogsLoc.findSubByLatLon(this.B.lat(),this.B.lng());
		                	 if (loc.parentLocation!=null) {
			                	 if (loc.parentLocation.subLocations.length>1 ||
			                			 loc.parentLocation.code!=currentCity.code) {
				                	 if (loc.parentLocation.code!=currentCity.code) {
				                		 addBackOnGMap(currentCity);
				                	 }else {
				                		 addBackOnGMap(loc.parentLocation);
				                	 }			                		 
				                	 locateSubGMapCode(null, loc.code);
				                	 selectLocation(loc.code, loc.city);
			                	 }
		                	 }
		                 });
		                 gogsLoc.locations[i].subLocations[j].marker=markers[k];
		                 GEvent.addListener(markers[k], "mouseover", function() {  
//alert(this.B.lat()+" "+this.B.lng());
		                	 //dumpProps(this,null);	                	 
		                	 var loc=gogsLoc.findSubByLatLon(this.B.lat(),this.B.lng()); 
		                	 this.openInfoWindowHtml("<div>"+loc.info+"</div>" ); 
		                 });
		                 GEvent.addListener(markers[k], "mouseout", function() {    
		                	 this.closeInfoWindow();  
		                 });
		                 gMap.addOverlay(markers[k]);
		                 k++;
                	 }
                 }
			 }
		}

function checkIfLocationsaLoaded(cityCode,time) {
	if (gogsLoc.allLocationsLoaded()) {
		onLoadMaps(cityCode);
	} else {
		setTimeout("checkIfLocationsaLoaded('"+cityCode+"');", time);	
	}
}

/* End GMAPS */

/* Load data about locations form database */
function refreshLocations() {
    var tsTimeStamp= new Date().getTime();
    var params={action: "get", time: tsTimeStamp};
    //params['num']='spl';
    var tableUrl="dataRetrival/getLocations.php";
    $.get(tableUrl, params, function(data){
    	var table=jQuery(data, document);
    	var rows=$(table).find("tr");
    	var len=rows.length;
    	var k=-1;
    	var city;
    	var oldNum='none';
    	var GML=new GMapLocation(null,null,null,null);
    	for (var i=0;i<len;i++) {
    		var cells=$(rows.get(i)).find("td");
    		var num=$(cells.get(0)).text();
    		var attr=$(cells.get(1)).text();
    		var val1=$(cells.get(2)).text();
    		var val2=$(cells.get(3)).text();
    		if (num!=oldNum) {
    			k++;
   				gogsLoc.locations[k]=new GMapLocation(val1,num,null,null);
    			oldNum=num;
    		} else {
    			if (attr=='CITY')  { 				
    				gogsLoc.locations[k].name=val1;
    			} else if (attr=='LAT') {
    				gogsLoc.locations[k].lat=val2;
    			}else if (attr=='LON') {
    				gogsLoc.locations[k].lon=val2;
    			} else if (attr=='ZOOM') {
    				gogsLoc.locations[k].zoom=val2;
    			}
    		}
    	}
    	refreshSubLocations();
    	table.remove();
    });    
}

function refreshSubLocations() {
	var len=gogsLoc.locations.length;
	for (var i=0;i<len;i++) {
		var tsTimeStamp= new Date().getTime();
		var params={action: "get", num: gogsLoc.locations[i].code, time: tsTimeStamp};
		var tableUrl="dataRetrival/getClubs.php";
		$.get(tableUrl, params, function(data){
	    	var table=jQuery(data, document);
	    	var rows=$(table).find("tr");
	    	var len2=rows.length;
	    	var k=-1;
	    	var city;
	    	var oldNum='none';	    
	    	var loc=gogsLoc.findByCode($(table).attr("num"));
	    	for (var j=0;j<len2;j++) {
	    		var cells=$(rows.get(j)).find("td");
	    		var num=$(cells.get(0)).text();
	    		var attr=$(cells.get(1)).text();
	    		var val1=$(cells.get(2)).text();
	    		var val2=$(cells.get(3)).text();
	    		var name=$(cells.get(5)).text();
	    		var longName=$(cells.get(6)).text();
	    		if (num!=oldNum) {
	    			k++;
	   				loc.subLocations[k]=new GMapLocation(val1,num,null,null);
	    			oldNum=num;
	    		} 	    		
	    		if (attr=='CITY')  { 	
	    			loc.subLocations[k].parentLocation=loc;
	    			loc.subLocations[k].city=val1;
	    			loc.subLocations[k].name=name;
	    			loc.subLocations[k].secondName=longName;
	    		} else if (attr=='LAT') {
	    			loc.subLocations[k].lat=val2;
	    		} else if (attr=='LON') {
	    			loc.subLocations[k].lon=val2;
	    		} else if (attr=='STREET') {
	               	var style;
	            	if (loc.subLocations[k].thumb=='dice_70_70_sh.png') {
	            		style='left:120px;top:0px;width:70px;height:70px;';
	            	} else {
	            		style='left:100px;top:0px;width:100px;height:70px;';
	            	}	
	    			loc.subLocations[k].street=val1; // zadnji zapis
	    			loc.subLocations[k].info="<p>"+loc.subLocations[k].name+"<br/>"+loc.subLocations[k].secondName+"<br/>"+loc.subLocations[k].street+"</p><img src='imgs3/gmapt/"+loc.subLocations[k].thumb+"' style='position:absolute;"+style+"'/>";
	    			//loc.subLocations[k].info=loc.subLocations[k].info.replace(/\"/g,'\\\"');
	    			//alert(loc.subLocations[k].info);
	    		} else if (attr=='THUMB') {
	    			loc.subLocations[k].thumb=val1;
	    		}
	    	}
	    	loc.subLoaded=true;
		});
	}
}


function allLocationsLoaded() {
    var ret=true;
	var len=this.locations.length;
    for (i=0;i<len;i++) {
    	if (!this.locations[i].subLoaded) {
    		ret=false;
    		break;
    	}
    }
    return ret;
}
/* End Load data about locations form database */

/* Help for close icons */
var album1=new ksAlbum("album1");
/* End Help for close icons */

/* Add back buton onw sub windows */
function addBackOnGMap(backToLocation) {
	if (!checkElements("#backOnGMap")) {
		$("<img id='backOnGMap' src='icons/play_left2r.png' style='position:absolute; top:2px; left:442px;' onclick='locateGMap(event,\""+backToLocation.code+"\"); selectLocation(\""+ backToLocation.code+"\",null);removeBackOnGMap();removeBackOnAbout();' " +
	    "onmouseout='album1.hoverEfectLROut2(event, this)' "+
	    "onmouseover='album1.hoverEfectLRIn2(event, this)' />").appendTo("#gmap_wrapper");
	}
	
}
	
function removeBackOnGMap() {
	if (checkElements("#backOnGMap")) {
		$("#backOnGMap").remove();
	}
}

function addBackOnAbout(backToLocation) {
	if (!checkElements("#backOnAbout")) {
		var left=parseInt($("#aboutLocations"+aboutLocationsCounter).css("width"));
		left=left-70;
		$("<img id='backOnAbout' src='icons/play_left2r.png' style='position:absolute; z-index:106;top:15px; left:"+left+"px;' onclick='locateGMap(event,\""+backToLocation.code+"\"); selectLocation(\""+ backToLocation.code+"\",null);removeBackOnGMap();removeBackOnAbout();' " +
	    "onmouseout='album1.hoverEfectLROut2(event, this)' "+
	    "onmouseover='album1.hoverEfectLRIn2(event, this)' />").appendTo("#aboutLocations"+aboutLocationsCounter);
	}
}
	
function removeBackOnAbout() {
	if (checkElements("#backOnAbout")) {
		$("#backOnAbout").remove();
	}
}

function addBackOnDisplay() {
	var onClick;
	if (whereWasI.currPlaceIs()=='news') {
		onClick='showDisplayFile("novosti_'+lang+'.html");'
	}
	if (!checkElements("#backOnDisplay")) {
		$("<img id='backOnDisplay' src='icons/play_left2r.png' style='position:absolute; z-index:106;top:15px; left:14px;' onclick='"+onClick+";removeBackOnDisplay();' " +
	    "onmouseout='album1.hoverEfectLROut2(event, this)' "+
	    "onmouseover='album1.hoverEfectLRIn2(event, this)' />").appendTo("#display"+displayIndex);
	}
}
	
function removeBackOnDisplay() {
	if (checkElements("#backOnDisplay")) {
		$("#backOnDisplay").remove();
	}
}
/* End Add back buton onw sub windows */

/* GMAP manipulating */
function showGMap(ev, cityCode, width, left) {
	var loc=null;
	if (!checkElements("#gmap_wrapper")) { // još nema GMape
	    $("<div id='gmap_wrapper' style='background:white;position:absolute;left:"+left+"px;top:-480px;z-index:1;width: "+width+"px; height: 450px'>\n\
	            <div id='gmap_canvas' style='position:absolute; left:2px; top:2px; width: "+(width-4)+"px; height: 446px'>\n\
	            </div>\n\
	       </div>").appendTo("#main"); 
	    dropFromAbove("#gmap_wrapper",-480,20);
	    //refreshLocations();
	    checkIfLocationsaLoaded(cityCode,100);
		loc=locateGMap(null, cityCode);
		if (loc==null) {
			loc=locateSubGMapCode(null, cityCode);
		}
	} else {	
		$("#gmap_wrapper").css("width",width+"px");
		$("#gmap_wrapper").css("left",left+"px");	
		$("#gmap_canvas").css("width",(width-4)+"px");		
	
		//if ($("#gmap_wrapper").css("top")>="600px") {
			resetToDrop("#gmap_wrapper", -480);
			loc=locateGMap(null, cityCode);
			if (loc==null) {
				loc=locateSubGMapCode(null, cityCode);
			}	
			dropFromAbove("#gmap_wrapper",-480, 20);
		//}

	}
    //onLoadMaps(cityCode);
    if (ev!=null) {
    	stopPropagate(ev);
    }
    return loc;
}

function repositionGMap(width, left) {
	$("#gmap_wrapper").css("width",width+"px");
	$("#gmap_wrapper").css("left",left+"px");	
	$("#gmap_canvas").css("width",(width-4)+"px");
}

var globalLat, globalLon, globalZoom;
function locateMapByGlobals() {
	gMap.setCenter(new GLatLng(globalLat, globalLon), globalZoom);
}

function locateGMap(ev, cityCode) {
	var loc=null;
	loc=gogsLoc.findByCode(cityCode);
	if (gMap!=null) {
		if (loc!=null) {
			globalLat=loc.lat;
			globalLon=loc.lon;
			globalZoom=parseInt(loc.zoom);
			gMap.setCenter(new GLatLng(loc.lat, loc.lon), parseInt(loc.zoom));
			//setTimeout("locateMapByGlobals();",2000);
			currentCity=loc;
		}
	} 
	return loc;
}

function locateSubGMapLatLon(ev, lat, lon) {
	var loc=null;
	loc=gogsLoc.findSubByLatLon(lat, lon);	
	if (gMap!=null) {
		if (loc!=null) {
			globalLat=loc.lat;
			globlLon=loc.lon;
			globalZoom=15;
			gMap.setCenter(new GLatLng(loc.lat, loc.lon), 15);
			//setTimeout("locateMapByGlobals();",2000);
			currentCity=loc;
		}
	}
	return loc;
}

function locateSubGMapCode(ev, code) {
	var loc=null;
	loc=gogsLoc.findSubByCode(code);
	if (gMap!=null) {			
		if (loc!=null) {
			globalLat=loc.lat;
			globlLon=loc.lon;
			globalZoom=15;
			gMap.setCenter(new GLatLng(loc.lat, loc.lon), 15);
			//setTimeout("locateMapByGlobals();",3000);
			currentCity=loc;
		}
	}
	return loc;
}

function removeGMapWrapper() {
	$("#gmap_wrapper").remove();
}

function closeGMap(ev) {
	var prevPlace=whereWasI.returnToPrevPlace();
	if (prevPlace=='croatia') {
		resetToDrop("#croatiaImage",-440);
		dropFromAbove("#croatiaImage",-440, 2);
		//TODO: clear aboutLocations and show info abotu croatia
		// $("#aboutLocationsContent").empty();
		if (desc!="" && desc!=null) {
			appendToAboutLocations(desc, true);
		}
		showAboutLocations();
	}if (prevPlace=='home') {
	}
	dropToHide("#gmap_wrapper",0,600,800,removeGMapWrapper);
    stopPropagate(ev);
}
/* End GMAP manipulating */



/* Writing data from database */
var CIAXRQ=null;
function writeClubInfo(code, append) {

//	if (!currentLocation.machines.loaded) {
//alert(1);		
//		setTimeout("writeClubInfo('"+code+"', "+append+")",100);
//		return;
//	}

	var tsTimeStamp= new Date().getTime();
	var params={action: "get", num: code, lng:lang, time: tsTimeStamp};
	var tableUrl="dataRetrival/getClubDesc.php";
	if (CIAXRQ!=null)  {
		CIAXRQ.abort();
	}
	CIAXRQ=$.get(tableUrl, params, function(data, getCIIndex){				
		var table=jQuery(data, document);    	
    	var row=$(table).find("tr").get(0);
    	var cell=$(row).find("td").get(0);
    	var desc=$(cell).html();    	
    	var top="20px";
    	if (append) {
    		top="100px";
    	}  	
    	desc="<div style='font-size:13px;line-height:17px;position:absolute;z-index:105;top:"+top+";left:20px;color:white;width:420px;height:120px;'>"+desc+"</div>";
		if (!append) {
			//$("#aboutLocationsContent").empty();
			appendToAboutLocations(desc, true);
		} else {
			// $(desc).appendTo("#aboutLocationsContent");
			appendToAboutLocations(desc, false);
		}
		selectLocationsInProgress=false;
		//onLocationMenuClick=false;
	});
}

/* End Writing data from database */

/* Main functions */
/* Locations */
var selectLocationsInProgress=false;
var onLocationMenuClick=false;
function selectLocation(location, parentLocationName, map) {
    removeByFilter(".album");
	if (selectLocationsInProgress) {
		return;
	}
	if (map=='undefined' || map==null) {
		map=true;
	}
	if (whereWasI.currPlaceIs()!='croatia' || map) { // TODO: ako je preko mape i izabermo grad, forisamo GMap, riješiti elegantnije
		if (whereWasI.currPlaceIs()!='location') {
			whereWasI.goToNewPlace('location', selectLocation, location, parentLocationName, map);
		} else {
			//whereWasI.replaceLastFunctionCall(selectLocation, location, parentLocationName, map);
			whereWasI.returnToPrevPlace();
			whereWasI.goToNewPlace('location', selectLocation, location, parentLocationName, map);
		}
		if (whereWasI.prevPlaceIs()=='croatia') {
			dropToHide("#croatiaImage",0,600,800,null);
			$("#mapOverFlash").remove();
		}
		//if (whereWasI.prevPlaceIs()=='aboutUs' || whereWasI.prevPlaceIs()=='news') {
			hideCurrDisplay();
		//}
	}
	var loc=null;
	currentParentLocation=parentLocationName; // 20100506
	if (parentLocationName!=null) {  // informacije o samom klubu, nije grad nego je klub 
		selectLocationsInProgress=true;
		//loc=gogsLoc.findSubByCode(location);
		//currentLocation=loc;
		//showGMap(null,currentLocation,480,500);
		//setTimeout("showGMap(null,currentLocation.code,480,500);",100);
		loc=showGMap(null,location,480,500);
		
		showAboutLocations(true);
		var desc="<h3>"+ parentLocationName+"</h3>";

		desc=desc+"<p>"+loc.name+"<br/>"+
		loc.secondName+", "+loc.street+"</p>";			
    	desc="<div style='position:absolute;z-index:105;top:30px;left:20px;color:white;'>"+desc+"</div>";

    	appendToAboutLocations(desc, true);
		currentLocation=loc;
		//currentLocation.machines.load(currentLocation.machines);    	
		writeClubInfo(location, true);
		addBackOnAbout(loc.parentLocation);
		//loc=locateGMap(null, location);
	} else {  // informacije o gradu i lokacijama
		if (map) { // forsiraj stvaranje mape
			loc=showGMap(null,location,705,275);	
		} else {
			loc=locateGMap(null, location);
		}
		var len=loc.subLocations.length;
		var desc="<h3>"+ loc.name+"</h3>";
		if (len>=1) {
			if (len==1) {
				repositionGMap(480,500);
				showAboutLocations(true);
				removeBackOnGMap();
				removeBackOnAbout();	
				desc=desc+"<a>"+loc.subLocations[0].name+"</a><br/>"+
				loc.subLocations[0].secondName+
				", <a>"+loc.subLocations[0].street+"</a><br/><br/>";	
				currentLocation=loc.subLocations[0];
				//currentLocation.machines.load(currentLocation.machines);
			} else {
				showAboutLocations(false);
				removeBackOnGMap();
				removeBackOnAbout();	
				for (var i=0; i<len; i++) {
					var subCode=loc.subLocations[i].code;
					var subCodeCity=loc.subLocations[i].city;
//alert(subCode);					
					desc=desc+"<div class='menu6' onclick='onLocationMenuClick=true;selectLocation(\""+subCode+"\", \""+subCodeCity+"\"); if (currentLocation.marker) currentLocation.marker.closeInfoWindow();' " +
							" onmouseout='if (!onLocationMenuClick) { var loc2=gogsLoc.findByCode(\""+location+"\").subLocations["+i+"];if (loc2.marker) loc2.marker.closeInfoWindow();}' onmouseover='if (!onLocationMenuClick) {var loc2=gogsLoc.findByCode(\""+location+"\").subLocations["+i+"];if (loc2.marker) loc2.marker.openInfoWindowHtml(\"<div>\"+loc2.info +\"</div>\")};'>";
					desc=desc+loc.subLocations[i].name+"<br/>"+
						loc.subLocations[i].secondName+
						", "+loc.subLocations[i].street+"<br/><br/></div>";			
					
				}				
			}
			
	    	desc="<div style='position:absolute;z-index:105;top:20px;left:20px;color:white;'>"+desc+"</div>";

			appendToAboutLocations(desc, true);
			$("div.menu6").bind("mouseout",function(){hoverDivBgImgOut(this);});
			$("div.menu6").bind("mouseover", function() {hoverDivBgImgIn(this, 'imgs/bg_menu6_bev2.png');})
			if (len==1) {
				writeClubInfo(loc.subLocations[0].code,true);
			}
		}
	}
}

/* End Locations */

/* About Location */
var aboutLocationsCounter=0;
var oldAboutLocationsCounter;
function showAboutLocations(defaultSize) {
	oldAboutLocationsCounter=aboutLocationsCounter;
	aboutLocationsCounter++;
	var oldName="aboutLocations"+oldAboutLocationsCounter;
	$("#"+oldName).stop(true,true);	
	dropToHide("#"+oldName,0,600,800,removeOldAboutLocation,oldName);
	//showAboutLocations(defaultSize);	
	var className='aboutLocations';
	var className2='aboutLocationsContent';	
	var xPos=430;
	if (defaultSize=="undefined" || defaultSize==null || !defaultSize) {
		className='aboutLocationsS';
		className2='aboutLocationsContentS';	
		xPos=210;
	}
	//if (!checkElements('#aboutLocations'+aboutLocationsCounter)) {
		$("<div id='aboutLocations"+aboutLocationsCounter+"' class='"+className+"'><img src='icons/xr.png' style='position:absolute; z-index:106;top:15px; left:"+xPos+"px;' onclick='closeLocation();'\n\
                onmouseout='album1.hoverEfectLROut2(event, this)'\n\
                onmouseover='album1.hoverEfectLRIn2(event, this)'\n\
            /><div id='aboutLocationsContent"+aboutLocationsCounter+"' class='"+className2+"' ></div></div>").appendTo("#main");	
        dropFromAbove("#aboutLocations"+aboutLocationsCounter,-480, 13);
    //}
/*
	$("#aboutLocations"+aboutLocationsCounter).stop(true,true);
	var className='aboutLocations';
	var className2='aboutLocationsContent';	
	var xPos=430;
	if (defaultSize=="undefined" || defaultSize==null || !defaultSize) {
		className='aboutLocationsS';
		className2='aboutLocationsContentS';	
		xPos=210;
	}
	if (!checkElements('#aboutLocations'+aboutLocationsCounter)) {
		$("<div id='aboutLocations"+aboutLocationsCounter+"' class='"+className+"'><img src='icons/xr.png' style='position:absolute; z-index:106;top:15px; left:"+xPos+"px;' onclick='closeLocation();'\n\
                onmouseout='album1.hoverEfectLROut2(event, this)'\n\
                onmouseover='album1.hoverEfectLRIn2(event, this)'\n\
            /><div id='aboutLocationsContent"+aboutLocationsCounter+"' class='"+className2+"' ></div></div>").appendTo("#main");	
        dropFromAbove("#aboutLocations"+aboutLocationsCounter,13);          
	} else {		
		oldAboutLocationsCounter=aboutLocationsCounter;
		aboutLocationsCounter++;
		showAboutLocations(defaultSize);	
		$("#aboutLocations"+oldAboutLocationsCounter).stop(true,true);
		dropToHide("#aboutLocations"+oldAboutLocationsCounter,600,800,removeOldAboutLocation);
	}
*/	
}

function appendToAboutLocations(desc, empty) {
	if (empty) {
		$("#aboutLocationsContent"+aboutLocationsCounter).empty();
	}
	$(desc).appendTo("#aboutLocationsContent"+aboutLocationsCounter);
}

function removeOldAboutLocation() {
	$("#aboutLocations"+oldAboutLocationsCounter).remove();
}

function removeOldAboutLocation(name) {
	$("#"+name).remove();
}

function closeLocation() {
	oldAboutLocationsCounter=aboutLocationsCounter;
	dropToHide("#aboutLocations"+oldAboutLocationsCounter,0,600,800,removeOldAboutLocation);
    if (checkElements('#gmap_wrapper')) {
    	dropToHide("#gmap_wrapper",0,600,800,null);
    }
    /*
    if (checkElements('#croatiaImage')) {
    	dropToHide("#croatiaImage",600,800,null);
    }*/
    $("#croatiaImage").remove();
    croatiaMap(false);
}
/* End Abotu Location */

/* Croatia Map */
function croatiaMap(overFlash) {
	if (!overFlash) {
		gogsStat.write('Odabir preko mape',null);
	}
	if (whereWasI.currPlaceIs()!='croatia') {
		whereWasI.goToNewPlace('croatia', croatiaMap, overFlash);
	}
	if (whereWasI.prevPlaceIs()=='news' || whereWasI.prevPlaceIs()=='aboutUs') {
		hideCurrDisplay();
	} else if ( !overFlash) {
		//gotoFlashFrame('00201', 'gota');
		if (checkElements('#mapOverFlash')) {
			$('#mapOverFlash').remove();
		}
	}
	if (whereWasI.prevPlaceIs()=='location') {
	    if (checkElements('#gmap_wrapper')) {
	    	dropToHide("#gmap_wrapper",0,620,800,null);
	    }
	}	
	if (checkElements('#mapOverFlash')) {
		$('#mapOverFlash').remove();
	}
    showCroatiaMap(overFlash);
}

function showCroatiaMap(overFlash) {
	var appendTo;
	var lat1=42.30;
	var lon1=13.3;
	var lat2=46.6;
	var lon2=19.5;
	if (overFlash) {	
	    if (!checkElements('#mapOverFlash')) {
	    	if (!checkElements('#croatiaImage')) {
	    		return; // ne postoji mapa, moža je korisnik odabrao pocetnu stranicu
	    	}
	    	$("<div id='mapOverFlash' style='position:absolute;width:490px;height:434px;left:500px;top:20px'></div>").appendTo("#main");
	    }
	    appendTo="#mapOverFlash";
	} else {
	    if (checkElements('#croatiaImage')) {
			$('#croatiaImage').remove();
	    }
            $("<div id='croatiaImage' style='position:absolute;width:490px;height:434px;left:500px;top:-440px'><img src='imgs/cro_560_500_green_bev_sh.png' style='width:500px;height:442px;' />").appendTo("#main");
	    appendTo="#croatiaImage";
	}
	var len=gogsLoc.locations.length;
	var item;	
	for (var i=0;i<len;i++) {
		d1=(lat2-lat1)/(gogsLoc.locations[i].lat-lat1);	
		y=434-(434/d1);
		d2=(lon2-lon1)/(gogsLoc.locations[i].lon-lon1);		
		x=490/d2;
		var	dimens='width:5px;height:5px;';
		var posName="top:"+Math.round(y-20)+"px;left:"+Math.round(x-10)+"px;";
		if (gogsLoc.locations[i].code=='zgb') {
			dimens='width:10px;height:10px;';
			posName="top:"+Math.round(y+7)+"px;left:"+Math.round(x-10)+"px;font-size:17px;"
		} else if (gogsLoc.locations[i].code=='smb') {
			posName="top:"+Math.round(y-13)+"px;left:"+Math.round(x-52)+"px;";
		} else if (gogsLoc.locations[i].code=='dgs') {
			posName="top:"+Math.round(y-13)+"px;left:"+Math.round(x+7)+"px;";
		}
		$("<div translate='yes' class='menu2' onmouseover='biggerDot(this);' onmouseout='smallerDot(this);'  style='position:absolute;"+posName+"z-index:102;' onclick='selectLocation(\""+gogsLoc.locations[i].code +"\",null,true);'>"+gogsLoc.locations[i].name+"</div>" +
		"<img src='icons/red_dot.png' style='"+dimens+"position:absolute;top:"+y+"px;left:"+x+"px;'/>" +
		"").appendTo(appendTo);		
	}
	if (appendTo=="#croatiaImage") {
	    dropFromAbove("#croatiaImage",-440, 20);
	}
}

function biggerDot(el) {
	var img=$(el).next("img");
	el.oldDim=img.css("width");
	el.oldX=img.css("left");
	el.oldY=img.css("top");
	img.css("width","12px");
	img.css("height","12px");
	if (el.oldDim=="10px") d=1; else d=3;
	img.css("left",parseInt(el.oldX)-d);
	img.css("top",parseInt(el.oldY)-d);
}

function smallerDot(el) {
	var img=$(el).next("img");
	img.css("width",el.oldDim);
	img.css("height",el.oldDim);
	img.css("left",el.oldX);
	img.css("top",el.oldY);	
}
/* End Croatia Map */

/* Blue Display Window */

function showDisplayFileLang(file) {
	var file2=file+'_'+lang+'.html';
	showDisplayFile(file2);
}

function showDisplayFile(file, big) {
	var newDisplay=showDisplay(true,big);
	//if (displayedFileOnDisplay!=file) {
		var tsTimeStamp= new Date().getTime();
		$.get('articles/'+file,{action: "get", time: tsTimeStamp}, function(data){
			$(data).appendTo(newDisplay);
			$("div.menu5").bind("mouseout",function(){hoverDivBgImgOut(this);});
			$("div.menu5").bind("mouseover", function() {hoverDivBgImgIn(this, 'imgs/bg_green3rb_480_20.png');})
			displayedFileOnDisplay=file;
		})
	//}
}

var displayedFileOnDisplay='none';
var displayIndex=0;
var oldDisplayIndex;
function showDisplay(contFlasOnClose, big) {
    if (typeof big == "undefined") {
        big = false;
    }
    var bgImg="bg_blue3_530_410_bev_sh.png";
    var positionStyle="left:235px;top:-390px;height:410px;width:530px;";
    var dropFromAbovePos=-390;
    var dropToPos=50;
    var closePos="top:15px; left:485px;";
    if (big) {
        bgImg="bg_830_510_blue3_bev_sh.png";
        positionStyle="left:95px;top:-560px;height:510px;width:830px;";
        dropFromAbovePos=-560;
        dropToPos=2;
        closePos="top:15px; left:785px;";
    }
    var onClickCode='closeDisplay();'; //croatiaMap(false);
    if (contFlasOnClose) {
        onClickCode=onClickCode+'croatiaMap(false);';// +'playFlash();';
    }
    var newDisplayDiv="<div id='display"+displayIndex+"' class='display' style='background-image:url(imgs/"+bgImg+");position:absolute;"+ positionStyle +"z-index:110;'>"+
    "<img src='icons/xr.png' style='position:absolute; z-index:106;"+closePos+"' onclick='"+onClickCode+"' "+
    "       onmouseout='album1.hoverEfectLROut2(event, this)' "+
    "       onmouseover='album1.hoverEfectLRIn2(event, this)' "+
    "    />"+
    "</div>";
    var newDisplay=$(newDisplayDiv).appendTo("#main");
    dropFromAbove(".display", dropFromAbovePos, dropToPos);
    //stopBlinking(".blinking");
    startBlinking(".blinking");
    return newDisplay;
}

/*
function showDisplayBig(contFlasOnClose) {
    showDisplay(contFlasOnClose,true);
}
*/

function removeOldDisplay() {
	$("#display"+oldDisplayIndex).remove();
}

function closeDisplay() {
	oldDisplayIndex=displayIndex;
	dropToHide(".display",0,600,800,removeOldDisplay);
}

function showDisplayDesc(machineCode) {
	var newDisplay=(false);
	if (machineCode!="") {
		var text;
		if (lang=='hr') {
			text='<p>Ispričavamo se. Podaci o automatu nisu unešeni!</p>';
		}
		if (lang=='en') {
			text='<p>Sorry. Information not provided!</p>';
		}
		var descDiv="<div id='displayContent"+displayIndex+"' class='displayContent' ></div>";
		$(descDiv).appendTo(newDisplay);
		$(text).appendTo("#displayContent"+displayIndex);
		/*
		var tsTimeStamp= new Date().getTime();
		var params={ action: "get", num: machineCode, time: tsTimeStamp };
		var tableUrl="dataRetrival/getMachineDesc.php";
		$.get(tableUrl, params, function(data){		
			var table=jQuery(data, document);    	
	    	var row=$(table).find("tr").get(0);
	    	var cell=$(row).find("td").get(0);
	    	var desc=$(cell).html();    	
	
			var descDiv="<div id='displayContent"+displayIndex+"' class='displayContent' ></div>";
			$(descDiv).appendTo("#display"+displayIndex);
			$(desc).appendTo("#displayContent"+displayIndex);
		});
		*/
	} 
}

function hideDisplay(display,fn) {
	dropToHide(display,0,600,800,fn);
	displayedFileOnDisplay='none';
}

function hideCurrDisplay() {
	dropToHide(".display",0,600,800,null);
	displayedFileOnDisplay='none';
}
/* End Blue Display Window */

/* About Us */
function aboutUs(file) {
	if (whereWasI.currPlaceIs()=='location') {
		dropToHide("#aboutLocations"+aboutLocationsCounter,0,600,800,null);
	    if (checkElements('#gmap_wrapper')) {
	    	dropToHide("#gmap_wrapper",0,620,800,null);
	    }
	}
	if (whereWasI.currPlaceIs()=='croatia') {
		if (checkElements('#croatiaImage')) {
			dropToHide("#croatiaImage",0,620,800,null);
		}
		dropToHide("#aboutLocations"+aboutLocationsCounter,0,600,800,null);
	}
	if (whereWasI.currPlaceIs()!='aboutUs') {
		whereWasI.goToNewPlace('aboutUs',aboutUs, file);	
		// fewWords
		// contact
		// opinions
	}	
	stopFlash();
	showDisplayFile(file);
}

/* News */
function news() {
        removeByFilter(".album");
        nagradnaRemove();
        dropAndRemove(".homeEvents");
	if (whereWasI.currPlaceIs()=='location') {
		dropToHide("#aboutLocations"+aboutLocationsCounter,0,600,800,null);
	    if (checkElements('#gmap_wrapper')) {
	    	dropToHide("#gmap_wrapper",0,620,800,null);
	    }
	}
	if (whereWasI.currPlaceIs()=='croatia') {
		if (checkElements('#croatiaImage')) {
			dropToHide("#croatiaImage",0,620,800,null);
			$("#mapOverFlash").remove();
		}
		dropToHide("#aboutLocations"+aboutLocationsCounter,0,600,800,null);
	}
	if (whereWasI.currPlaceIs()!='news') {
		whereWasI.goToNewPlace('news',news);	
	}
	stopFlash();
	showDisplayFile("novosti_"+lang+".html");
}

/* End Main Functions */

/* Main Menu */
var currentMenu='none';
var clearMenuTimerId=null;
function createMenuSneek(xPos,yPos,height,what) {
	var xPos2=xPos+155+"px";
	var xPos3=xPos+310+"px";
	var yPos2=yPos+"px";
	var height2=height+"px";
	var numOfCards=1;
	var menuSneek;
	menuSneek="<div id='menuSneek"+what+"' class='menus' style='position:absolute; z-index:200;left:"+xPos+";top:"+yPos+";height:"+height2+";width:180px;overflow:hidden'>"+
			  " <div id='menuImage' style='position:absolute;top:224px;left:0px;width:170px;height:190px;'>" +
			  "	 <img  src='imgs3/herz_as_sg_r10_sh.png' style='position:absolute;top:0px;left:0px;z-index:1'/>"+
			  "	 <div style='position:absolute;top:10px; left:10px;z-index:2'width:170px;height:190px;>";
	menuSneek2="<div id='menuSneek2"+what+"' class='menus' style='position:absolute; z-index:199;left:"+xPos2+";top:"+yPos+";height:"+height2+";width:180px;overflow:hidden'>"+
	  " <div id='menuImage2' style='position:absolute;top:224px;left:0px;width:170px;height:190px;'>" +
	  "	 <img  src='imgs3/karo_as_sg_r10_sh.png' style='position:absolute;top:0px;left:0px;z-index:1'/>"+
	  "	 <div style='position:absolute;top:10px; left:10px;z-index:2'width:170px;height:190px;>";
	menuSneek3="<div id='menuSneek3"+what+"' class='menus' style='position:absolute; z-index:198;left:"+xPos3+";top:"+yPos+";height:"+height2+";width:180px;overflow:hidden'>"+
	  " <div id='menuImage3' style='position:absolute;top:224px;left:0px;width:170px;height:190px;'>" +
	  "	 <img  src='imgs3/m_herz_cetvorka_sg_r_sh.png' style='position:absolute;top:0px;left:0px;z-index:1'/>"+
	  "	 <div style='position:absolute;top:10px; left:10px;z-index:2'width:170px;height:190px;>";

	if (what=='croatia') {
		var len=gogsLoc.locations.length;
		for (var i=0;i<len;i++) {
			menuSneek=menuSneek+"<div class='menu3'  onclick='stopFlash();selectLocation(\""+gogsLoc.locations[i].code +"\",null);'>"+ gogsLoc.locations[i].name +"</div>";
		}
		menuSneek=menuSneek+"<div style='font-size:6px'>___________________________________________</div>";
		menuSneek=menuSneek+"<div class='menu3' onclick='stopFlash();croatiaMap(false);'>"+langResources["locationsMap"]+"</div>";

	}	

	if (what=='machines' && whereWasI.currPlaceIs()!='location') {
		var len=gogsMachines.length();
		var menuCardId='menuCard1';
		var menuItem="";
		//alert(len);
		for (var i=0;i<len;i++) {
			if (i>10 && i<=21) {
				menuCardId='menuCard2';
			} else if (i>21) {
				menuCardId='menuCard3';
			}
			menuItem="<div id='"+menuCardId+"' class='menu3' style='font-size: 11px;' onclick='stopFlash();showDisplayDesc(\""+gogsMachines.get(i).num+"\")'>"+ gogsMachines.get(i).name2 +"</div>";
			if (i>10 && i<=21) {
				menuSneek2=menuSneek2+menuItem;
				numOfCards=2;
			} else if (i>21) {
				menuSneek3=menuSneek3+menuItem;
				numOfCards=3;
			} else {
				menuSneek=menuSneek+menuItem;	
			}
		}

	} else if (what=='machines' && whereWasI.currPlaceIs()=='location' && currentLocation!=null) {	
		var len=currentLocation.machines.length();
		var menuCardId='menuCard1';
		var menuItem="";
		//alert(len);
		for (var i=0;i<len;i++) {
			if (i>10 && i<=20) {
				menuCardId='menuCard2';
			} else if (i>20) {
				menuCardId='menuCard3';
			}
			menuItem="<div id='"+menuCardId+"'  class='menu3' style='font-size: 11px;' onclick='stopFlash();showDisplayDesc(\""+currentLocation.machines.get(i).num+"\")'>"+ currentLocation.machines.get(i).name2 +"</div>";
			if (i>10 && i<=20) {
				menuSneek2=menuSneek2+menuItem;
				numOfCards=2;
			} else if (i>20) {
				menuSneek3=menuSneek3+menuItem;
				numOfCards=3;
			} else {
				menuSneek=menuSneek+menuItem;	
			}
		}
	}
	
	if (what=='home') {
		menuSneek=menuSneek+"<div style='text-align:center;' onclick='goHome();'>"+langResources['goHomeHelp']+"</div>";
	}
	
	if (what=='o_nama') {
		menuSneek=menuSneek+"<div class='menu3' onclick='aboutUs(\"o_nama_"+lang+".html\");'>"+langResources['fewWordsAboutUs']+"</div>";
		menuSneek=menuSneek+"<div class='menu3' onclick='aboutUs(\"kontakt_"+lang+".html\");'>"+langResources['contact']+"</div>";
		menuSneek=menuSneek+"<div class='menu3' onclick='aboutUs(\"pohvale_"+lang+".html\")'>"+langResources['opinion']+"</div>";
	}
	
	if (what=='news') {
		menuSneek=menuSneek+"<div style='text-align:center;width:145px;' onclick=''>"+langResources['newsAndEventsHelp']+"</div>";
	}
	
	menuSneek=menuSneek+"</div>" +			  
			  " </div>"+
			  "</div>";
	$(menuSneek).appendTo("#main");
	
	if (numOfCards>1) {
		menuSneek2=menuSneek2+"</div>" +			  
		  " </div>"+
		  "</div>";
		$(menuSneek2).appendTo("#main");
	}
	
	if (numOfCards>2) {	
		menuSneek3=menuSneek3+"</div>" +			  
		  " </div>"+
		  "</div>";
		$(menuSneek3).appendTo("#main");
	}
	$("div.menu3").bind("mouseout",function(){hoverDivBgImgOut(this);});
	$("div.menu3").bind("mouseover", function() {hoverDivBgImgIn(this, 'imgs/bg_menu3rb16.png');})

}

function createMenu(what, xPos, yPos, height, autoRemove, milisec) {
	if (currentMenu==what || currentMenu=='remove') {
		return;
	}
	removeMenu(currentMenu); // first do remove becuse it resets currentMenu
	currentMenu=what;
	//setTimeout('createMenuSneek('+xPos+','+yPos+','+height+',\"'+what+'\");dropFromUnder("#menuImage",0,10,400);',115);
	createMenuSneek(xPos,yPos,height,what);
	dropFromUnder("#menuImage",0,10,500);
	if (checkElements("#menuImage2")) {
		setTimeout('dropFromUnder("#menuImage2",0,10,500);',50);
	}
	//dropFromUnder("#menuImage2",0,10,500);
	if (checkElements("#menuImage3")) {
		setTimeout('dropFromUnder("#menuImage3",0,10,500);',150);
	}
	//dropFromUnder("#menuImage3",0,10,500);
	if (autoRemove) {
		var xImg="<img src='icons/xr.png' style='position:absolute; z-index:106;top:15px; left:135px;' onclick='removeMenu(\""+what+"\")' "+
	        "       onmouseout='album1.hoverEfectLROut2(event, this)' "+
	        "       onmouseover='album1.hoverEfectLRIn2(event, this)' "+
	        "    />";
		if (checkElements("#menuImage3")) {
			$(xImg).appendTo("#menuImage3");
		} else if (checkElements("#menuImage2")) {
			$(xImg).appendTo("#menuImage2");
		} else {
			$(xImg).appendTo("#menuImage");
		}
		if (milisec=='undefined' || milisec==null) {
			milisec=10000; // 10 sekundi
		}
		removeMenuTimer(what, milisec);
	}
}


function removeMenu(what) {

	$('div.menus').remove();
	if (clearMenuTimerId!=null) {
		clearTimeout(clearMenuTimerId);
		clearMenuTimerId=null;
	}
	currentMenu='none';
}

function removeMenuTimer(what, milisec) {
	if (clearMenuTimerId!=null) {
		clearTimeout(clearMenuTimerId);
	}
	if (milisec=='undefined' || milisec==null) {
		milisec=10000; // 10 sekundi
	}
	clearMenuTimerId=setTimeout('removeMenu("'+what+'");clearMenuTimerId=null;', milisec);
}
/* End Main Menu */

/* Animations */
function resetToDrop(filter, newTop) {
/*	var top=parseInt($(filter).css("height"));
	if (top>0) {
		top=(-1*top)+"px"
	}	else {
		top="-580px";
	}
    */
    var top=newTop+"px";
    $(filter).css("top",top);
}

function resetToDropUnder(filter, top) {
	var newTop=top+"px"
	$(filter).css("top",newTop);
}

function dropToHide(filter, currTop, finalTop, speed,func, param1) {
	$(filter).stop(true,true);
        var delta="+="+(finalTop-currTop)+"px";
	$(filter).animate({top:delta},speed, function(){
		if (func!=null) {
			if (typeof(param1)=='undefined') {
				func();
			} else {
				func(param1);
			}
		}
	});
}

// TODO popravi tako da uzme currTop od skrivenog (1.) ili predaj currTop kao parameter (prije to drugo
function dropFromAbove(filter, currTop, finalTop) {
	$(filter).stop(true,true);
	//if (parseInt($(filter).css("top"))>0) {
	//	resetToDrop(filter);
	//}(filter)
        //var currTop=parseInt($(filter).css("top"));
        var delta=finalTop-currTop;
	var firstTop="+="+ (delta+30) +"px"; //(finalTop+30)+"px";
	var secondTop="-=50px"; //(finalTop-20)+"px";
	var thirdTop="+=20px"; //finalTop+"px";
	$(filter).animate({top:firstTop},800, function(){$(filter).animate({top:secondTop},200,function(){$(filter).animate({top:thirdTop},100, function(){
            for(var i=0;i<$(filter).length;i++) {
                if (parseInt($($(filter).get(i)).css("top"))>=300) {
                    $($(filter).get(i)).remove();                   
                } 
            }
        });onLocationMenuClick=false;});}); //fadeIn();
        // TODO onaj display koji izalzi van ili je na manj od 2/3 briši
}

function dropFromUnder(filter, finalTop, firstDelta, firstSpeed) {
	$(filter).stop(true,true);
	var firstTop=(finalTop-firstDelta)+"px";
	var secondDelta=firstDelta/2;
	var secondTop=(finalTop+secondDelta)+"px";
	var thirdTop=finalTop+"px";
	var secondSpeed=firstSpeed/4;
	var thirdSpeed=secondSpeed/1;
	var elements=$(filter);
	elements.animate({top:firstTop},firstSpeed, function(){elements.animate({top:secondTop},secondSpeed,function(){elements.animate({top:thirdTop},thirdSpeed);});}); //fadeIn();
}
/* End Animations */

function goHome() {
        $(".remove").remove();
        $(".album").remove();
        $(".album").remove();
	$("div").stop(true, false);
	$("img").stop(true, false);
        ClearAllTimers();
        /*
        clearTimeout(homePageEventsTimer);
        clearTimeout(nagradnaIgraTimer);
        */
        $(".homeEvents").stop(true,true);
        $(".homeEvents").remove();
        ShowCurrentEvents();
	if (checkElements("#croatiaImage")) {
		$("#croatiaImage").remove();
	}
	if (checkElements("#mapOverFlash")) {
		$("#mapOverFlash").remove();
	}
	if (checkElements("#aboutLocations"+aboutLocationsCounter)) {
		$("#aboutLocations"+aboutLocationsCounter).remove();
	}
	if (checkElements("#gmap_wrapper")) {
		$("#gmap_wrapper").remove();
	}
	closeDisplay();
	if (whereWasI.currPlaceIs()=='home') {
		actionFlash('strt');
                //gotoFlashFrame('00001', 'gota');
                //playFlash();
		return;
	}
	//} else if (whereWasI.currPlaceIs()=='croatia') {
	//	closeLocation();
	//} else if (whereWasI.currPlaceIs()=='location') {
	//closeLocation();
	//}
	whereWasI.goHome();
	setTimeout("actionFlash('strt');",800);
	onReady();
}

/**/
function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) {var msg = parent + "." + i + "\n" + obj[i];} else {var msg = i + "\n" + obj[i];}
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) {return;}
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) {dumpProps(obj[i], parent + "." + i);} else {dumpProps(obj[i], i);}
      }
   }
}

function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function getActionFromFlash(action) {
	if (action=='start') {
		$("#div0").css("top","0px");
		var img=new Image(579,512);img.src='imgs/cro_560_500_green_bev_sh.png';
	}
	if (action=='movieAt200' ) {  // && whereWasI.currPlaceIs()=='home'
		if (checkElements("#croatiaImage")) {
			$("#croatiaImage").remove();
		}
		$("<img id='croatiaImage' src='imgs/cro_560_500_green_bev_sh.png' style='position:absolute;top:248px;left:495px; width:50px;height:44px;'/>").appendTo("#main");
		$("#croatiaImage").animate({left:"500px",top:"20px",width:"490px",height:"433px"},6000,function(){croatiaMap(true);});
	}
}



function gotoFlashFrame(frame, act){		
	// act- goto , gota (go to grame only if curent farme bigger -5 )
	var object=$("#mainBackgroundImage object");
	//alert(e2.get(0));
	object.get(0).sendActionToFlash(act+':'+frame);
 }

function stopFlash(){		 
	var object=$("#mainBackgroundImage object");
	//alert(e2.get(0));
	object.get(0).sendActionToFlash('stop');
}

function playFlash(){		 
	var object=$("#mainBackgroundImage object");
	//alert(e2.get(0));
	object.get(0).sendActionToFlash('play');
}

function actionFlash(act){		 
	var object=$("#mainBackgroundImage object");
	//alert(e2.get(0));
	object.get(0).sendActionToFlash(act);
}


var nagradnaIgraTimer;
function destroyNIgra() {
    $("#NIgra").remove();
}

function nagradnaRemove() {
    dropToHide("#NIgra",0, 700, 800,destroyNIgra);
    //$("#NIgra").remove();
}

function removeByFilter(filter) {
    dropToHide(filter,0, 700, 800,destroyNIgra);
    //$("#NIgra").remove();
}


function removeIt(element) {
    $(element).remove();
}

function dropAndRemove(element) {
    dropToHide(element,0, 700, 800, removeIt, element);
    //$("#NIgra").remove();
}

var blinking=false;
function startBlinking(element) {
    blinking=true;
    blinkStep1(element);
}

function stopBlinking(element) {
    blinking=false;
    $(element).stop(true, true);
}


function blinkStep1(element) {
    if (!blinking) {
        return;
    }
    $(element).fadeTo('slow',0.3).fadeTo('slow',1, function(){blinkStep1(element)});
    //function(){
    //    blinkStep2(element);
    //});
}

function blinkStep2(element) {
    if (!blinking) {
        return;
    }
    $(element).fadeTo('slow',1, function(){
        blinkStep1(element);
    });
}

function  nagradna() {
        clearTimeout(nagradnaIgraTimer);
        $("#NIgra").remove();
        $("<div id='NIgra' class='homeEvents' style='z-index:2000; position:absolute;left:250px;top:-400px; background-image:url(imgs/bg_red_gogs_500_380_op90_6.png);width:530px;height:410px;overflow: visible;'>"
        +"<div class='menu6' style='z-index:2001;font-size: 15px; padding-top:8px; position: absolute; height: 50px; top:343px; left:323px; text-align:center;' onclick='clearTimeout(homePageEventsTimer);nagradnaRemove();showDisplayFile(\"nagradna_pravila.html\", true);'>Pravila nagradne igre</div>"
        +"<img src='icons/xg.png' style='position:absolute;top:15px; left:485px;' onclick='nagradnaRemove();' "+
        "       onmouseout='album1.hoverEfectLROut2(event, this)' "+
        "       onmouseover='album1.hoverEfectLRIn2(event, this)' "+
        "    />"
        +"<div id='blinkText' style='width:530px;position:relative; top:155px;left:-5px;overflow: visible;'>"
        + "<div  style='width:530px;position:relative; top:0px; left:-5px;font-size: 88px;height:130px;overflow: visible;"
           + "color: faf708;"
           + "font-family: Arial,Helvetica,sans-serif;"
           + "font-weight: bold;"
           + "text-align: center;'>2.000.000</div>"
           + "<div style='width:530px;position:absolute; top:88px; left:-5px; font-size: 36px;height:40px;"
           + "color: faf708;"
           + "font-family: Arial,Helvetica,sans-serif;"
           + "font-weight: bold;"
           + "text-align: center;'>NAGRADNIH KREDITA</div>"
        +"</div></div>").appendTo("#div0");
        blinkStep1('#blinkText');
        dropFromAbove("#NIgra",-400, 50);
}

function loadTemplate(file) {
    var tsTimeStamp= new Date().getTime();
    $.get(file,{
        action: "get",
        time: tsTimeStamp
    }, function(data){
        $(data).appendTo("#display"+displayIndex);
        $("div.menu5").bind("mouseout",function(){
            hoverDivBgImgOut(this);
        });
        $("div.menu5").bind("mouseover", function() {
            hoverDivBgImgIn(this, 'imgs/bg_green3rb_480_20.png');
        })
    })
}

var hp;
var homePageEventsTimer;
function homePageEvents(template) {
    //removeByFilter(".album");
    eval(template.beforeLoad);
    //nagradnaRemove();
    //clearTimeout(homePageEventsTimer);
    // TODO pročitaj textove za evenet na naslovnoj strani
    // 1. linija naslov
    // 2. Blinking text, veči dio i manji dio
    // 3. linija dodatno pojašanjenje, kratko
    // 4. link na detalje
    //$(".homeEvents").remove();
    $.get(template.url,{
        action: "get",
        time: new Date().getTime()
    }, function(data){
        var newDisplay=$(data).appendTo("#div0");
    	for (var key in template.classes) {
            $(newDisplay).find("."+key).append(template.classes[key]);
    	}
        $(newDisplay).find(".closeX").click(function() {
          eval(template.onClose);
        });
    	for (var key in template.jsVariables) {
            eval(key+"='"+template.jsVariables[key]+"'");
    	}       
        eval(template.onLoad);
        /*
        dropFromAbove(".homeEvents", -400, 50);
        stopBlinking(".blinking");
        startBlinking(".blinking");
        */
    });
    return;
}

function homePageEventsLevel2(template, name) {
    //removeByFilter(".album");
    // eval(template.beforeLoad);
    //nagradnaRemove();
    //clearTimeout(homePageEventsTimer);
    // TODO pročitaj textove za evenet na naslovnoj strani
    // 1. linija naslov
    // 2. Blinking text, veči dio i manji dio
    // 3. linija dodatno pojašanjenje, kratko
    // 4. link na detalje
    //$(".homeEvents").remove();
    $.get(template.url,{
        action: "get",
        time: new Date().getTime()
    }, function(data){
        var newDisplay=$(data).appendTo("#main");
        $(newDisplay).attr("id", name);
    	for (var key in template.classes) {
            $(newDisplay).find("."+key).append(template.classes[key]);
    	}
    	for (var key in template.jsVariables) {
            eval(key+"='"+template.jsVariables[key]+"'");
    	}
        $(newDisplay).css("top",template.yPos);
        $(newDisplay).css("left",template.xPos);
        $(newDisplay).click(function() {
          eval(template.onClick);
        });
        // eval(template.onLoad);
        /*
        dropFromAbove(".homeEvents", -400, 50);
        stopBlinking(".blinking");
        startBlinking(".blinking");
        */
    });
    return;
}


function onReady() {
	gogsStat.write('Pocetna stranica',null);
}

function animatePBar() {
	setTimeout("animatePBar();",50);
}

function go() {
        $.getJSON("templates.js", function(data){ // učitaj promjenjive podatke 
        Templates=data;
            reposition();
            refreshLocations();
            onReady();
            ShowCurrentEvents();
    });
}

$(document).ready(function(){
    go();
});

function reposition() {
    var mainWidth=parseInt($("#div0").css("width"));
    var oldMainLeft=parseInt($("#div0").css("left"));
    var winWidth=$(window).width();
    var d;
    if (winWidth>mainWidth) {
        d=parseInt((winWidth-mainWidth)/2);
        $("#div0").css("left",d+"px");
    } else {
        $("#div0").css("left","0px");
        d=0;
    }
}



