var ismobile = false;
$(document).ready(function(){

    // is it mobile device?
    ismobile = is_touch_device();
    
    // init background
    if(background && background.length > 0){
        init();
        loading_init();
    }
    
    // dropdown in main navigation
    $('#mainnav > li').each(function () {
        var $target = $(this).children('.sub-menu');
        if($target.length > 0){
    		$(this).hover(function () {
    			$target.slideToggle('fast');
    		}, function () {
    			$target.slideToggle('fast');
    		});
		}
	});
	
    if(ismobile){
        // don't do fixed element on mobile device (except background)
        $('#topbar, #sidebar_fixed').css({'position':'absolute'});
        $('#footer').css({'position':'relative','marginTop':'-30px'});
        
        $(window).scroll(function(e){
            var $win = $(this);
            //$('#background').css({'position':'absolute','top':$win.scrollTop()});
	        $img = $('#background').find('img.isactive');
	        resizeImage($img);
        });
        
    }else{
        // make fixed element move when scroll horizontal
    	$(window).scroll(function(e){
            horizontalScroll($(this));
        });
        
        $(window).resize(function(e){
            horizontalScroll($(this));
	        $img = $('#background').find('img.isactive');
            resizeImage($img);
        });
    }
    
    // smooth scrolling to anchor tag
	var locationPath = filterPath(location.pathname);
	var scrollElem = scrollableElement('html', 'body');
	$('a[href*=#]').each(function() {
	   if($(this).hasClass('lightbox-inline'))return true;
		var thisPath = filterPath(this.pathname) || locationPath;
		if (  locationPath == thisPath
			&& (location.hostname == this.hostname || !this.hostname)
			&& this.hash.replace(/#/,'') ) {
			var $target = $(this.hash), target = this.hash;
			if (target) {
				var targetOffset = $target.offset().top;
				$(this).click(function(event) {
					event.preventDefault();
					$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
						location.hash = target;
					});
				});
			}
		}
	});
	// end smooth scrolling
});

// apply loading background image
function loading_init(){
   $('#background').addClass('loading');
}

var imgloaded = false;
$(window).load(function(){
   imgloaded = true;
   $('#background').removeClass('loading');
   if(background.length == 1){
      showImage($('#background img'));
   }else{
      rotate_bg();
   }
});

// make fixed element move when scroll horizontal
function horizontalScroll($win){
    if($.browser.msie && $.browser.version=="6.0") return true;
    var winWidth, $nav;
            
    $nav = $("#topbar, #footer, #sidebar_fixed");
    
    $nav.each(function(){
        if($(this).css('position') == 'fixed'){
            winWidth = $win.width();
            var navWidth = $(this).width();
            $(this).css( "left", ($win.scrollLeft() * -1) );
        }
    });
}

// init background
function init(){
    if(background.length == 1){
        $('#background').append('<img src="'+background[0]+'" class="isactive" />');
   }else if(background.length > 1){
        $bgs = $('<div id="background-slide"></div>');
        $.each(background, function(key, value){
            $bgs.append('<img src="'+value+'" />');
        });
        $('#background').append($bgs);
   }
}

// show background image, only when it's loaded
function showImage($img){
    var iw = $img.width();
    var ih = $img.height();
    
    if(!iw || !ih){
        setTimeout(function(){ showImage($img); },100);
    }else{ 
        resizeImage($img);
        $img.fadeIn();
    }
}

// resize background image to fit viewport
function resizeImage($img){
    var ww = $(window).width();
    var wh = $(window).height();

    //$img.css({'width':'auto','height':'auto'});
    
    var iw = $img.width();
    var ih = $img.height();
    
    var wratio = (ww / iw).toFixed(2);
    var hratio = (wh / ih).toFixed(2);
    
    if(wratio > hratio){
        iw = iw * wratio;
        ih = ih * wratio;
    }else{
        iw = iw * hratio;
        ih = ih * hratio;
    }
    
    $img.css({'width': (iw+5)+'px','height': (ih+5)+'px'});
}

// play background slideshow
function rotate_bg(){
    var $active_slide =$('#background-slide img.isactive');
    if($active_slide.length != 1){
        showImage($('#background-slide img:eq(0)'));
        $('#background-slide img:eq(0)').addClass('isactive');
    }else{
        if(imgloaded){
            var $target = $($active_slide.next());
            $active_slide.fadeOut(1000);
            
            $active_slide.removeClass('isactive');
            
            if($target.length != 1){
                $target = $('#background-slide img:eq(0)');
            }
            
            showImage($target);
            $target.addClass('isactive');
        }else{
            setTimeout('rotate_bg()', 500);
            return false;
        }    
    }
    setTimeout('rotate_bg()', 8000);
}

// dumb way to figured out if background image is loaded
function is_all_loaded(){
    $('#background').find('img').each(function(){
        if(!$(this).width() || !$(this).height())return false;
    });
    return true;
}

// if it's a touch device, must be mobile
function is_touch_device() {  
  try {  
    document.createEvent("TouchEvent");  
    return true;  
  } catch (e) {  
    return false;  
  }  
}

// smooth scrolling to anchor tags
function filterPath(string) {
	return string
	.replace(/^\//,'')
	.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
	.replace(/\/$/,'');
}

function scrollableElement(els) {
	for (var i = 0, argLength = arguments.length; i <argLength; i++) {
		var el = arguments[i],
		$scrollElement = $(el);
		if ($scrollElement.scrollTop()> 0) {
			return el;
		} else {
			$scrollElement.scrollTop(1);
			var isScrollable = $scrollElement.scrollTop()> 0;
			$scrollElement.scrollTop(0);
			if (isScrollable) {
				return el;
			}
		}
	}
	return [];
}
