/**
 * @author Raduly Botond
 */
//Mediabox vars
var mbopen = false;
var map;
var cookieObject = new Object();
var cookieOptions = { path: "/", duration: 0 };
//Env -> host and protocol
var myImage = new Array(), dImage, loadedImages = new Array(), mainMenuSleep, loaderSleep, fimageSleep, loadingImages = new Array();
var bungalowSrvHost = window.location.host;
var bungalowSrvProt = location.protocol;
var tipsAndLastViewedHousesLoaded = false;


window.addEvent("domready", function () {
    //initsearch
    cookieObject.hf = new Object();

    if (Cookie.read("searchquery") != null && Cookie.read("searchquery") != "undefined" && Cookie.read("searchquery") != "") {
        cookieObject = JSON.decode(Cookie.read("searchquery"));
        if (cookieObject != null && cookieObject != "undefined") {
            if (cookieObject.mins != null && cookieObject.mins != "undefined") { selectedClassification = cookieObject.mins - 1 }
            if (cookieObject.minb != null && cookieObject.minb != "undefined") { sliderPosIndex = cookieObject.minb - 1 }
        }
    }
    if (issetObj(Cookie.read("searchquery"))) {        
        homepage = false;
    } else {
        homepage = true;
    }
    
    checkForCookie([{ "cn": "kerstpopup", "cdir": "kerst" }, { "cn": "nieuwjasje", "cdir": "nieuwjasje"}]);
    //Main menu
    var flineMenu = $('mainmenu');
    var headerImageBannerContainer = $('header-bungalow-galery');
    var firstImage = headerImageBannerContainer.getElement('img')
    var currentHover = -1;
    var currentMenuImageVisible = firstImage;
    flineMenu.getElements('a').each(function (val, index) {
        if (val.className != "more") {
            val.index = index;
            val.addEvent("mouseenter", function () {
                clearTimeout(mainMenuSleep);
                clearTimeout(loaderSleep);
                clearTimeout(fimageSleep);
                currentHover = val.index;
                mainMenuSleep = setTimeout(function () {
                    try {
                        if (typeof myImage[val.index].src != "undefined" && currentMenuImageVisible.src != myImage[val.index].src && loadedImages[val.index]) {
                            currentMenuImageVisible.setStyle("display", "none");
                            myImage[val.index].setStyle("display", "block");
                            currentMenuImageVisible = myImage[val.index];
                        }
                    } catch (err) { }
                }, 400)
                if (!loadedImages[val.index] && !loadingImages[val.index]) {
                    loaderSleep = setTimeout(function () {
                        loadingImages[val.index] = true;
                        var imgElement = new Element('img', { src: imagesHeadGal[val.index], width: "385px", height: "285px" });
                        imgElement.addEvent("load", function () {
                            myImage[val.index] = imgElement;
                            loadedImages[val.index] = true;
                            if (val.index == currentHover) {
                                currentMenuImageVisible.setStyle("display", "none");
                                myImage[val.index].setStyle("display", "block");
                                currentMenuImageVisible = this;
                            } else {
                                myImage[val.index].setStyle("display", "none");
                            }
                        })
                        imgElement.inject(headerImageBannerContainer);
                    }, 200)
                }
            })
        }
    })
    flineMenu.addEvent("mouseleave", function () {
        clearTimeout(mainMenuSleep);
        currentHover = -1;
        clearTimeout(loaderSleep);
        fimageSleep = setTimeout(function () {
            currentMenuImageVisible.setStyle("display", "none");
            firstImage.setStyle("display", "block");
            currentMenuImageVisible = firstImage;
        }, 200)
    })
    //submenu
    var submenu = $("submenu");
    var currentSubHovered = -1;
    var currentSelected = -1;
    var loadedSubmenuImages = Array();
    var loadingSubmenuImages = Array();
    var mySubmenuImages = Array();
    submenu.getElements('a').each(function (val, index) {
        val.index = index;
        val.addEvent("mouseenter", function () {
            clearTimeout(mainMenuSleep);
            clearTimeout(loaderSleep);
            clearTimeout(fimageSleep);
            currentHover = val.index;
            mainMenuSleep = setTimeout(function () {
                try {
                    if (typeof mySubmenuImages[val.index].src != "undefined" && currentMenuImageVisible.src != mySubmenuImages[val.index].src && loadedSubmenuImages[val.index]) {
                        currentMenuImageVisible.setStyle("display", "none");
                        mySubmenuImages[val.index].setStyle("display", "block");
                        currentMenuImageVisible = mySubmenuImages[val.index];
                    }
                } catch (err) { }
            }, 400)
            if (!loadedSubmenuImages[val.index] && !loadingSubmenuImages[val.index]) {
                loaderSleep = setTimeout(function () {
                    loadingSubmenuImages[val.index] = true;
                    var imgElement = new Element('img', { src: imagesHeadGalSpecial[val.index], width: "385px", height: "285px" });
                    imgElement.addEvent("load", function () {
                        mySubmenuImages[val.index] = imgElement;
                        loadedSubmenuImages[val.index] = true;
                        if (val.index == currentSubHovered) {
                            currentMenuImageVisible.setStyle("display", "none");
                            mySubmenuImages[val.index].setStyle("display", "block");
                            currentMenuImageVisible = this;
                        } else {
                            mySubmenuImages[val.index].setStyle("display", "none");
                        }
                    })
                    imgElement.inject(headerImageBannerContainer);
                }, 200)
            }
        })
    })
    submenu.addEvent("mouseleave", function () {
        clearTimeout(mainMenuSleep);
        currentHover = -1;
        clearTimeout(loaderSleep);
        fimageSleep = setTimeout(function () {
            currentMenuImageVisible.setStyle("display", "none");
            firstImage.setStyle("display", "block");
            currentMenuImageVisible = firstImage;
        }, 200)
    });
    //Tip position Last viewed
    if (issetObj($("dvTipsAndLwHouses"))) {
        new ScrollSpy({
            min: Math.round($(window).getScrollSize().y * 0.7) - window.size().height,
            onEnter: function (position, state, enters) {
                if (!tipsAndLastViewedHousesLoaded) {
                    //set this to true so if the user scrolls down a second time we don't load it twice
                    tipsAndLastViewedHousesLoaded = true;
                    //tip houses and last viewed house
                    PageMethods.GetTipAndLastViewedHouses(selectedLanguage, function (response) {
                        $('dvTipsAndLwHouses').setProperty("html", response);
                        $('dvTipsAndLwHouses').setStyle("height", "169px");
                        //run javascript related to tip and lw houses
                        initTipSlider();
                    }, function (error) { })
                }
            }
        });
    }
})
/*------ General functions */
function initTipSlider() {
    var sliderVieportElements = 6;
    var sliderCont = $("tipslider");
    var tipsMainContainer = $("sliderCont");
    var allContainer = $("tiplastcontainer");
    var arrWindow = $("arr-tooltipwindow");
    var arrWindowFX = new Fx.Morph(arrWindow).set("opacity", "0");
    var arrWindowInside = $("arr-twinside");
    arrWindowFX.animating = false;
    arrWindowFX.firstTimeAnimating = true;
    arrWindowFX.addEvent("complete", function () {
        this.animating = false;
    })

    if (issetObj(sliderCont)) {
        var sliderContChilds = sliderCont.getChildren(tipsMainContainer);
        var noelements = sliderContChilds.length;
        var buttonLeft = $("tipright");
        var buttonRight = $("tipleft");

        var firstElementOnViewPort = 1;
        var isAnimating = false;
        var increment = 0;
        var leftPosition = 0;
        var fxSlidAnimation = new Fx.Tween(sliderCont);
        fxSlidAnimation.addEvent("complete", function () {
            isAnimating = false;
        })
        arrWindow.addEvents({
            mouseenter: function () {
                if (arrWindowFX.animating) { arrWindowFX.cancel() }
                arrWindowFX.animating = true;
                arrWindowFX.start({ "opacity": "1", "top": "165px" });
            },
            mouseleave: function () {
                clearInterval(fxSlideTimeout);
                fxSlideTimeout = setTimeout(function () {
                    if (arrWindowFX.animating) { arrWindowFX.cancel() }
                    arrWindowFX.animating = true;
                    arrWindowFX.start({ "opacity": "0", "top": "170px" });
                }, 20);
            }
        })
        var fxSlideTimeout = null;
        if (noelements > sliderVieportElements) {
            for (i = 0; i < sliderVieportElements; i++) {
                var duplicate = sliderContChilds[i].clone();
                duplicate.inject($(sliderCont));
            }

            buttonLeft.addEvent("click", function () {
                if (!isAnimating) {
                    if (firstElementOnViewPort > noelements) {
                        firstElementOnViewPort = 2;
                        sliderCont.setStyle('left', "0px");
                        leftPosition = 0;
                    }
                    else {
                        firstElementOnViewPort++;
                    }
                    leftPosition -= 150;
                    fxSlidAnimation.start("left", leftPosition + "px");
                    isAnimating = true;
                }
            });
            buttonRight.addEvent("click", function () {
                if (!isAnimating) {
                    if (firstElementOnViewPort == 1) {
                        sliderCont.setStyle('left', "-" + (noelements * 150) + "px");
                        leftPosition = (noelements * 150) * -1;
                        firstElementOnViewPort = noelements;
                    }
                    else {
                        firstElementOnViewPort--;
                    }
                    leftPosition += 150;
                    fxSlidAnimation.start("left", leftPosition + "px");
                    isAnimating = true;
                }
            });
        } else {
            buttonLeft.setStyle("display", "none");
            buttonRight.setStyle("display", "none");
        }
        //info window functionality
        var sliderContMask = sliderCont.getElements(".pricemask");
        sliderContMask.each(function (e, i) {
            e.addEvents({
                mouseenter: function (evnt) {
                    var elmPos = this.getPosition().x - allContainer.getPosition().x;
                    clearInterval(fxSlideTimeout);
                    var cElm = this;
                    fxSlideTimeout = setTimeout(function () {
                        if (arrWindowFX.animating) { arrWindowFX.cancel() }
                        $("arr-tooltipwindow").setStyle("left", (elmPos - 53) + "px");
                        var avaiblabilities = cElm.getParent().getElement("ul").clone();
                        arrWindowInside.innerHTML = "";
                        arrWindowInside.adopt(avaiblabilities);
                        arrWindowFX.animating = true;
                        arrWindowFX.start({ "opacity": "1", "top": "165px" });
                        arrWindowFX.firstTimeAnimating = false;
                    }, 300)
                },
                mouseleave: function (evnt) {
                    clearInterval(fxSlideTimeout);
                    if (arrWindowFX.animating) { arrWindowFX.cancel() }
                    if (!arrWindowFX.firstTimeAnimating) {
                        arrWindowFX.animating = true;
                        arrWindowFX.start({ "opacity": "0", "top": "170px" });
                    }
                }
            })
        })
    }
}
function checkForCookie(cookieName) {
    var cookieObj, title;
    cookieName.each(function(item, index) {
        if (!mbopen) {
            cookieObj = Cookie.read(item.cn)
            if (issetObj(cookieObj) && cookieObj != 0 && cookieObj != 2) {
                title = ((cookieObj.indexOf("_") != -1) ? cookieObj.replace(/[_]/gi, "::") : "::");
                Cookie.write(item.cn, '0', { duration: 360, path: "/" });
                Mediabox.open(bungalowSrvProt + '//' + bungalowSrvHost + '/scriptsv2/overlay/SpecialDiscounts.aspx?lang=' + mainLanguageCode + '&action=' + item.cdir, '', '400 380 false ' + title);
                mbopen = true
                if (item.cn == "kerstpopup") { Cookie.dispose("kerstpopup"); }
            }
        }
    })
}
function issetObj(obj){return (obj!=null && obj!="undefined")?true:false;}

function addRemoveIconList(obj){
	if (cookieObject.hf[obj.name]!=null || cookieObject.hf[obj.name]!=undefined){
		delete cookieObject.hf[obj.name];
		return false;
	} else {
		cookieObject.hf[obj.name] = 1;
		return true;
	}
}


function getRedirectLocation(){
	var req = bungalowSrvProt+"//"+bungalowSrvHost+"/scriptsv2/json/sf_getcount.aspx";	
	Cookie.write("searchquery", JSON.encode(cookieObject), cookieOptions)
	jsonSearchRequest = new Request.JSON({
		url: req,
		onSuccess: function(jresponse, text){
			if (jresponse != null) {
				window.location = jresponse.link;
			}
		},
		onFailure:function(){				
		}
    }).get({ "lid": selectedLanguage, "guid": guid(), "nocount": "0" });
}
/* SEO redirect functions */
function linkGoto(linkLocation, linkTarget) {
    linkTarget = (typeof linkTarget == "undefined") ? false : linkTarget;
    if (linkTarget) {
        window.open(linkLocation);
    } else {
        var stub_object = new Element('span', { 'html': linkLocation.replace('&lang','&amp;lang') });
        var ret_val = stub_object.get('text');
        delete stub_object;
        window.location = ret_val;
    }
}
function scrollToElement(elmId) {
    var scroll = new Fx.Scroll(window, { wait: false, duration: 400, transition: Fx.Transitions.Quad.easeInOut });
    scroll.toElement($(elmId));
}
function openCustomMediaBox(url, width, height, title, scrollBool) {    
    Mediabox.open(url, '', width + ' ' + height + ' ' + scrollBool + ' ' + title);
    return false;
}
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
