/*/function openScroll(url) {
	params = 'width=' + 640 + ', height=' + 480 + ', scrollbars=yes, location=yes, menubars=yes, resizable=yes, toolbar=yes, status=yes';
	popup = window.open(url, "openScroll", params);
	popup.focus();
}*/
var tempMsgTemplate = "<div style='border: 1px solid black; padding: 5px; background: white'></div>";

/**
 *template za loadanje fotogalerija, mape itd
 */
var ajaxLoadingTemplate = "<div class=\"overlay\">" +
    "<div class=\"dragHandle\" style=\"background-color: #DDDDDD; text-align: right;\n\
    cursor: move\"><a href=\"javascript:;\"><img src='/web/histrica/images/close_big.gif' border='0' /></a></div>" +
    "<div class=\"ajaxContent\"></div>";
    
/**
 * Booking
 */
function bookingSend(form){
	var form = $(form);
	$(".ajax-loader", form).show();
	$("input[type='submit']", form).attr("disabled", "disabled");
	$.post("/web/histrica/booking.php", $(form).serialize(), function(data){
		$(".ajax-loader", form).hide();
		$("input[type='submit']", form).removeAttr("disabled");
		var response = eval('('+data+')');
		if(response.sent == 1)
		{
			$("input[type='text'], textarea", form).val("");
			var ts = new Date().getTime();
			$(".captcha-image", form).attr("src", "/web/histrica/captcha/capimg.php?"+ts);
			$.fancybox({
				'content' : response.message,
				'showCloseButton' : false
			});
		} else if(response.error) {
			alert(response.error);
		} else {
			alert("Greška.");
		}
	});
	return false;
}
    
/**
 * skracuje textove u glavnim tabovima na max 11 znakova
 */
$(function(){
	$("#col2 #main_tabnav a").each(function(){
		var text = $(this).text();
		
		if(text.length > 11)
		{
			$(this).text(text.substring(0,10)+'...');
		}
	});
});
    
/**
 * radi http post
 * @param inputSelector koja polja treba oposlati kao parametre, npr: "#bookingTab :input"
 * @param callbacks array funkcija koja se izvrsava nakon request-a {success: function(), error: function()}
 * ima jedan parametar, vraceni rezultat , npr function(myHtml) {....}
 * @param dataType tip rezultata
 * @param url
 */
function doPost(inputSelector, url, callbacks, dataType) {
    var fields = $(inputSelector).serializeArray();
    var postData = {};
    //var txt = "";
    jQuery.each(fields, function(i, field){
        postData[field.name] = field.value;
    //txt = txt + ";" + field.name + "=" + field.value;
    });
        
    $.ajax({
        type: "POST",
        url: url,
        dataType: (dataType)?dataType:"html",
        data: postData,
        success: function(response) {
            if (callbacks && callbacks.success) {
                callbacks.success(response);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // typically only one of textStatus or errorThrown 
            // will have info
            if(typeof(textStatus)!='undefined'){
                alert(textStatus);
            }
            if(typeof(errorThrown)!='undefined'){
                alert("Error name: " + errorThrown.name 
                    + ". Error message: " + errorThrown.message);
            }
            if (callbacks && callbacks.error) {
                callbacks.error();
            }
        },
        complete: function() {
            if (callbacks && callbacks.complete) {
                callbacks.complete();
            }
        }
    });
}

/**
 * izmjenjuje css vrijednost između 2 stanja
 * @param elementSelector jquery selector
 * @param property css property koji treba switchati
 * @param value1 prva vrijednost
 * @param value2 druga vrijednost
 */
function toggleCssProperty(elementSelector, property, value1, value2) {
    var elem = $(elementSelector);
    if (elem.length == 0) return;
    var currentValue = elem.css(property);
    if (currentValue == value1) {
        elem.css(property, value2);
    }else {
        elem.css(property, value1);
    }
}

/*******************************************************************************
 * sekcija koja submita form i kreira tabove tražilice
 *******************************************************************************/              
var lastSearch;
function doSearch() {
    lastSearch = new Date();
    var loadId = $.cc.showTempMessage({
        template: tempMsgTemplate,
        message: "Pretra\u017eujem ponudu, molim pricekajte....",
        toggleSpeed: "slow",
        center: true
    });
    doPost("#searchFormContainer :input",
        //"/ui/simplesearch.jsp",
        $("#searchFormContainer form").attr("action"),
        {
            success: searchCallback,
            complete: function() {
                $.cc.removeTempMessage(loadId);
            }
        },
        "html");
}
            
function searchCallback(response) {
    addSearchResult(response);
    
}
            
function addSearchResult(response) {
    var searchEnd = new Date();
    var $lastTab = $("#searchesTabbar li:last");
    var lastIndex = "0";
    if ($lastTab.size() > 0) {
        lastIndex = $lastTab.attr("rel");
    }
    var index = parseInt(lastIndex);
    index++;
    var tabId = "searchtab-" + index;
    $("<div></div>").attr("id", tabId).appendTo("#searchesContainer").html(response);
    $("#searchesTabbar").tabs("add", "#" + tabId, " " + index + " ");
    //var newSearchContent = document.getElementById(tabId);
    //newSearchContent.innerHTML = response;
    var $newTab = $("#searchesTabbar li:last");
    $newTab.attr("rel", index);
    var closeButt = $("<img src=\"/web/histrica/images/close.gif\" alt=\"x\"/>")
    .click(function() {
        closeTab(tabId);
    });
    $newTab.append(closeButt);
    $("#searchesTab").show();
    $("#main_tabnav").tabs("select", "#searchesContainer");
    var renderEnd = new Date();
    //alert("sadrzaj duzine: " + response.length +
    //    ", dobavljen sa servera u: " + (searchEnd.getTime() - lastSearch.getTime()) +
    //   "ms, a renderiran u: " + (renderEnd.getTime() - searchEnd.getTime()) + "ms");
    /*var newSearchContent = document.createElement("div");
                        newSearchContent.className = "maincontent";
                        newSearchContent.setAttribute("id", uniqueId);
                        newSearchContent.innerHTML = response;
                        var maincontent = document.getElementById("maincontent");
                        maincontent.parentNode.insertBefore(newSearchContent, maincontent); */
    //counts the opened searches
    //var tabsCollection = $("#search-contentNav li");
    //var searchIndex = 1;
    //if (tabsCollection.length > 1) {
    //    lastTab = tabsCollection.get(tabsCollection.length - 1);
    //    searchIndex = parseInt($(lastTab).attr("rel")) + 1;
    //}
    //$("#search-contentNav").tabs("add", '#' + uniqueId,
    //    " <span class=\"leftbg\"></span> " + searchIndex + " <span class=\"rightbg\"></span> ");
    //$("#search-contentNav").tabs("select", '#' + uniqueId);
    //var closeButt = $("<a class=\"closetab\" href=\"javascript:;\"><img src=\"/web/images/closetab.gif\" alt=\"x\"/></a>")
    //.click(function() {
    //    closeTab(uniqueId);
    //});
    //alert($("#search-contentNav li:last").length);
    //$("#search-contentNav li:last").append(closeButt).attr("rel", searchIndex);
    //procjenjuje širinu tabova, tako da se ne preklapa u drugi red
    //zatvara najstariju pretragu ako je to slučaj
    while(closeExcessTabs()){}
}

/**
 * zatvara pocetne tabove ako njihova ukupna širina nadilazi širinu panela 
 * pa se nemogu vidjeti...
 * @return true ako je jedan tab zatvoren
 */
function closeExcessTabs() {
    var navWidth = 0;
    $("#searchesTabbar li").each(function(i) {
        navWidth = navWidth + $(this).outerWidth({
            margin: true
        });
    });
    if (navWidth > $("#col2").width()) {
        removeSearch($($("#searchesTabbar li").get(0)).attr("rel"));
        $("#searchesTabbar").tabs("remove", 0);
        $.cc.showTempMessage({
            template: tempMsgTemplate,
            message: "Otvorili ste previse pretraga, najstarija je automatski zatvorena!",
            toggleSpeed: "slow",
            center: false,
            timeoutPeriodSec: 3
        });
        return true;
    }
    return false;
}

function removeSearch(searchIndex) {
    //alert("Removing search : " + searchIndex);
    $.ajax({
        type: "GET",
        url: "/ui/removeSearch.jsp?searchIndex=" + searchIndex,
        dataType: "text"
        /*error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }*/
    });
}

function closeTab(contentId) {
    //alert("closing: " + contentId);
    $("#searchesTabbar li").each(function(i) {//svaki tab
        var searchIndex = $(this).attr("rel");
        $(this).find("a").each(function(j) {//svaki link u tabu, u principu su 2
            var el = $(this);
            if (el.attr("href").indexOf("#" + contentId)!=-1) {
                $("#searchesTabbar").tabs("remove", i);
                removeSearch(searchIndex);
            } 
        });
    });
    if ($("#searchesTabbar li").size() == 0) {
        //maknute sve pretrage
        $("#searchesTab").hide();
        $("#main_tabnav").tabs("select", 0);
    }
}

function gotoSearchPage(searchKey, pageIndex, locale) {
    $("#" + searchKey + "_table").slidePanel("destroy");
    var loadId = $.cc.showTempMessage({
        template: tempMsgTemplate,
        message: "Učitavam stranicu, molim pričekajte....",
        toggleSpeed: "slow",
        center: false
    });
    $.ajax({
        type: "GET",
        url: "/ui/simplesearch.jsp",
        dataType: "html",
        data: {
            searchKey: searchKey,
            PAGE: pageIndex,
            locale: locale,
            format: "short"
        },
        success: function(response) {
            //var contentId = $("#" + searchKey).parent("div").attr("id");
            var searchContent = document.getElementById(searchKey);
            searchContent.innerHTML = response;
            $("#" + searchKey).ensureVisible({
                scrollSpeed: 1200
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // typically only one of textStatus or errorThrown 
            // will have info
            if(typeof(textStatus)!='undefined'){
                alert(textStatus);
            }
            if(typeof(errorThrown)!='undefined'){
                alert("Error name: " + errorThrown.name 
                    + ". Error message: " + errorThrown.message);
            }
        },
        complete: function() {
            $.cc.removeTempMessage(loadId);
        }
    });
}
/*******************************************************************************
 * kraj sekcije koja submita form i kreira tabove tražilice
 * *****************************************************************************
 * Početak sekcije koja dodaje u favorite
 *******************************************************************************/
function addPage2Favorites(contentType, resourceId, locale) {
    var loadId = $.cc.showTempMessage({
        template: tempMsgTemplate,
        message: "Spremam va\u0161 odabir u favorite....",
        toggleSpeed: "slow",
        center: true
    });
                    
    $.ajax({
        type: "GET",
        url: "/"+locale+"/favorites.jspa",
        dataType: "html",
        data: {
            task: "add",
            t: contentType,
            i: resourceId,
            locale: locale
        },
        complete: function() {
            $.cc.removeTempMessage(loadId);
        },
        success: function(response) {
            $.cc.showTempMessage({
                template: tempMsgTemplate,
                message: "Stranica uspje\u0161no spremljena u favorite!",
                toggleSpeed: "slow",
                center: true,
                timeoutPeriodSec: 2
            });
            $('.box1 ul.tabnav').tabs("url", 1, "/"+locale+"/favorites.jspa?task=list&i=" + resourceId + "&t=" + contentType + "&locale=" + locale);
            $('.box1 ul.tabnav').tabs("select", 1);
            setTimeout("$('.box1 ul.tabnav').tabs('load', 1);", 500);
            //$('.box1 ul.tabnav').tabs("load", 1);
        },
        error: function(xmlHttpRequest, textStatus, errorThrown) {
            alert("Error adding to favorites: " + xmlHttpRequest.status);
        }
    });
}

//brise stranicu iz favorita
function removeFromFavorites(contentType, resourceId) {
    var loadId = $.cc.showTempMessage({
        template: tempMsgTemplate,
        message: "Bri\u0161em stranicu iz favorita....",
        toggleSpeed: "slow",
        center: true
    });

    $.ajax({
        type: "GET",
        url: "/ui/favorites.jspa",
        dataType: "html",
        data: {
            task: "remove",
            t: contentType,
            i: resourceId
        },
        complete: function() {
            $.cc.removeTempMessage(loadId);
        },
        success: function(response) {
            $.cc.showTempMessage({
                template: tempMsgTemplate,
                message: "Stranica uspje\u0161no pobrisana iz favorita!",
                toggleSpeed: "slow",
                center: true,
                timeoutPeriodSec: 2
            });
            $('.box1 ul.tabnav').tabs('load', 1);
        },
        error: function(xmlHttpRequest, textStatus, errorThrown) {
            alert("Error in communication: " + xmlHttpRequest.status);
        }
    });
}

function toggleFavorites(tabbarId) {
    $("#" + tabbarId + "_offer").toggle();
    $("#" + tabbarId + "_pages").toggle();
    toggleCssProperty("#" + tabbarId + "_offer_link", "font-weight", "bold", "");
    toggleCssProperty("#" + tabbarId + "_pages_link", "font-weight", "bold", "");
}

/*******************************************************************************
 * Kraj sekcije koja dodaje u favorite
 *******************************************************************************/
