var ua = navigator.userAgent.toLowerCase();
var isOpera = (ua.indexOf('opera') > -1);
var isIE = (!isOpera && ua.indexOf('msie') > -1);

function addEvent(obj, type, fn) {
    if (obj.addEventListener)
        obj.addEventListener(type, fn, false);
    else if (obj.attachEvent)
        obj.attachEvent( "on"+type, fn );
}

function isChildNode(elem, sell) {
    for (var childItem in elem.childNodes) {
        if (elem.childNodes[childItem].nodeType == 1) {
            if (elem.childNodes[childItem] == sell)
                return true;
            else if (isChildNode(elem.childNodes[childItem], sell))
                return true;
        }
    }
    return false;
}

function getViewportHeight() {
    return ((document.compatMode || isIE) && !isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : document.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
}

function getDocumentHeight() {
    return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight : document.documentElement.scrollHeight, getViewportHeight());
} 

function ddlInit() {
    $(".ddl div").each(function() {
        var ddl = $(this);
        var curLbl = ddl.find(".current");
        var list = ddl.find("ul");
		
        curLbl.click(function() {
            curLbl.hide();
            list.show();
        });
        list.click(function() {
            curLbl.show();
            list.hide();
        });
        list.find("li").click(function() {
            curLbl.text($(this).find("a").text());
            curLbl.show();
            list.hide();
        });
		
        var sell = this;
        addEvent(document, 'click', function(event){
            var event = event || window.event;
            var t = event.target || event.srcElement;
			
            if (t!=sell && !isChildNode(sell, t)) {
                curLbl.show();
                list.hide();
            }
        });
		
    });
}

function getPopup() {
    $("#overlay").css({
        height: getDocumentHeight()
    }).show().click(function() {
        closePopup()
    });
    $('#popup').show();
}

function closePopup() {
    $("#overlay, #popup").hide();
}

function roll(lnk) {
    var list = $("#right-menu ul");
    switch (lnk.id) {
        case "home":
            list.css({
                backgroundPosition: "left -175px"
            });
            break;
        case "food":
            list.css({
                backgroundPosition: "left -350px"
            });
            break;
        case "sports":
            list.css({
                backgroundPosition: "left -525px"
            });
            break;
        case "about":
            list.css({
                backgroundPosition: "left -700px"
            });
            break;
        case "gallery":
            list.css({
                backgroundPosition: "left -875px"
            });
            break;
        case "blog":
            list.css({
                backgroundPosition: "left -1050px"
            });
            break;
        case "contact":
            list.css({
                backgroundPosition: "left -1225px"
            });
            break;
    }
}

function norm() {
    $("#right-menu ul").css({
        backgroundPosition: "left top"
    });
}

function changePanelState() {
    var panel = $("#left-form");
    if (panel.hasClass("opened")) {
        panel.animate({
            left: "-344px"
        }, 400).removeClass("opened");
        panel.find("div.label").removeClass("opened");
    }
    else {
        panel.animate({
            left: "0px"
        }, 400).addClass("opened");
        panel.find("div.label").addClass("opened");
    }
}

function customDdlInit() {
    $(".dropdown").each(function() {
        var ddl = $(this);
        var curVal = ddl.find(".curVal");
        var list = ddl.find("ul");
        var items = ddl.find("li");
        var input = ddl.find(":input").first();
		
        curVal.click(function() {
            if (curVal.hasClass("opened")) {
                list.hide();
                curVal.toggleClass("opened");
            }
            else {
                list.show();
                curVal.toggleClass("opened");
            }
        })
		
        items.click(function() {
            var item = $(this);
            curVal.text(item.text());
            input.val(item.text());
            list.hide();
            curVal.toggleClass("opened");
        });
		
        var sell = this;
        addEvent(document, 'click', function(event){
            var event = event || window.event;
            var t = event.target || event.srcElement;
			
            if (t!=sell && !isChildNode(sell, t)) {
                list.hide();
                curVal.toggleClass("opened");
            }
        });
		
    });
}



$(document).ready(function() {
    // Bind resize of overlay to window resize
    $(window).bind('resize', function() {
        $("#overlay").css({
            height: getDocumentHeight()
        });
    });

    // Init language select
    ddlInit();
    customDdlInit();

    // Init background slideshow
    /*
    $.fn.supersized.options = {
        transition: 1,
        startwidth: 1024,
        startheight: 768,
        minsize: .5,
        slideshow: 1,
        slideinterval: 7000
    };
    $('#supersize').supersized();
    */

    // Add hover effects to main-menu
    $('#right-menu ul li a').each(function(){
        $(this).hover(
            function(){
                roll(this);
            },
            function(){
                norm();
            }
            );
    });

    // prepare subscribe form
    $('#subscribe-form #subscribe-submit').click(function() {
        // validate 
        var error = false;
        $('#subscribe-form :input').each(function() {
            if ($(this).attr('name') == 'email') {
                if (! /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/.test($(this).val())) {
                    $(this).addClass('error');
                    $(this).bind('change', function(){
                        $(this).removeClass('error')
                    });
                    error = true;
                }
            }
        });
        // Stop propogation if error acquired
        if (error) {
            return false;
        }
        // submit the form
        $('#subscribe-form').ajaxSubmit({
            success: function(responseValue) {
                $('#subscribe-form').fadeOut(300, function(){
                    if (/.*ERROR.*/.test(responseValue)) {
                        $('#subscribe-error').fadeIn(300);
                    } else {
                        $('#subscribe-success').fadeIn(300);
                    }
                });
            }
        });
        // return false to prevent normal browser submit and page navigation
        return false;
    });

    // prepare booking form
    $('#booking-date').datepicker({
        dateFormat: 'mm/dd/yy',
        numberOfMonths: 1,
        minDate: 0,
        maxDate: '+3M'
    });
    $('#booking-form #booking-submit').click(function() {
        // validate
        var error = false;
        $('#booking-form :input').each(function() {
            switch ($(this).attr('name')) {
                case 'email':
                    if (! /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/.test($(this).val())) {
                        $(this).addClass('error');
                        $(this).bind('change', function(){
                            $(this).removeClass('error')
                        });
                        error = true;
                    }
                    break;

                case 'first-name':
                case 'last-name':
                case 'phone':
                case 'persons':
                case 'date':
                case 'time':
                    if (!$(this).val() || $(this).val() == 'mm/dd/yy') {
                        $(this).addClass('error');
                        $(this).bind('change', function(){
                            $(this).removeClass('error')
                        });
                        error = true;
                    }
                    break;
            }
        });
        // Stop propogation if error acquired
        if (error) {
            return false;
        }
        // submit the form
        $('#booking-form').ajaxSubmit({
            success: function(responseValue) {
                $('#booking-form').fadeOut(300, function(){
                    if (/.*ERROR.*/.test(responseValue)) {
                        $('#booking-error').fadeIn(300);
                    } else {
                        $('#booking-success').fadeIn(300);
                    }
                });
            }
        });
        // return false to prevent normal browser submit and page navigation
        return false;
    });

    // initialize bg slideshow
    new SlideShow(images, $('#background-slideshow'));

    // initialize gallery
    /*$('#gallery-container a').lightBox({
        imageLoading: '/public/themes/clayhills/images/lightbox-ico-loading.gif',
	imageBtnClose:'/public/themes/clayhills/images/lightbox-btn-close.gif',
	imageBtnPrev: '/public/themes/clayhills/images/lightbox-btn-prev.gif',
	imageBtnNext: '/public/themes/clayhills/images/lightbox-btn-next.gif'
    });
    $('#gallery').click(function(){
        $('#gallery-container a').first().click();
        return false;
    });*/
		
		
		$('.gallery-wrapper br').remove();
		$('.gallery-wrapper a').lightBox({
        imageLoading: '/public/themes/clayhills/images/lightbox-ico-loading.gif',
				imageBtnClose:'/public/themes/clayhills/images/lightbox-btn-close.gif',
				imageBtnPrev: '/public/themes/clayhills/images/lightbox-btn-prev.gif',
				imageBtnNext: '/public/themes/clayhills/images/lightbox-btn-next.gif'
    });
		
		
		
		var newsItemDur = 7000;
	
		function revolveNews(parent, index) {
			var nextindex = (index == $(parent).children('div:not(#newsblock-seal)').length-1) ? 0 : index+1;
			$(parent).children('div:not(#newsblock-seal)').css({
				'opacity': 0,
				'display': 'block',
				'z-index': 1
			});
			$('div:not(#newsblock-seal):eq('+index+')', $(parent)).css('z-index',2);
			$('div:not(#newsblock-seal):eq('+index+')', $(parent)).animate({
				opacity: 1
			}, 1000, function() {
				$(this).delay(newsItemDur).animate({
					opacity: 0,
				}, 1000, function(){
					revolveNews(parent,nextindex);
				});
			});
		}
		
		
		var news_imgs = new Array();
		$('#newsblock > div:not(#newsblock-seal)').each(function(){
			
			var img_src = $('img',this).attr('src');
			var img_w = (110/$('img', this).outerHeight())*$('img', this).outerWidth();
				var pi = Math.PI;
				var rad = 2.5*(pi/180);
				var img_top = Math.sin(rad)*(img_w/2);
				
			news_imgs.push([img_src, img_w, img_top]);
			$('img', this).hide();
			
		});
		
		$('#newsblock > div:not(#newsblock-seal)').each(function(i,e){
			
			var paper = Raphael($(this).get(0), news_imgs[i][1]+25, 144);
			var c = paper.image(news_imgs[i][0], 6, 9+news_imgs[i][2], news_imgs[i][1], 110);
			c.rotate(2.5);
			$('*:nth-child(3)',this).css('margin-top', 25);
			
		});
		
		if ($('#newsblock').length > 0) {
			revolveNews('#newsblock', 0);
		}
});
