/*-***********************************-*
 * Learnosity Common JavaScript
 *-***********************************-*/
var console = console || { log: function(){} };

$(function () {
    // Global focus on user name input if found
	$('.username:first').focus();
    
    $('#langselect').change(function() {
        window.location.href = $(this).attr('data-langselect') + this.value;
    });
    
    /* Generic include of jQueryUI Calendar (override with custom global class) */    
    $(".datepicker").datepicker({
    	dateFormat: 'yy-mm-dd',
    	constrainInput: true
    });
    
    /* Generic Modal 
    $('.modal').each(function(){
    	
    	var this_iframe = $(this).data('colorbox_iframe') ? $(this).data('colorbox_iframe') : false;
    	var this_href = $(this).attr('href');
    	$(this).colorbox({
    		href: this_href,
    		iframe: this_iframe
    		
    	});
    	
    });
    */
    	
    $('.modal').live('click',function(e){
    	var self = $(this);
    	var isAssetIFrame = self.data('colorbox_asset_iframe') || false;
    	var data = {};
    	
    	if (isAssetIFrame) {
    		data = {
    			href: self.attr('href') + '?displaymode=lightwindow&requestType=iFrame',
    			iframe: true,
    			width: 500,
    			height: 500
    		};
    	}
    	else {
    		data = {
    			href: self.attr('href') 
    		};
    	}
    	
    	$(this).colorbox(data);
    	e.preventDefault();
    });
    
    
    
    /* Image modal (signle not gallery) */
	$('.imagemodal').each(function() {
		var imageUrl = $(this).attr('data-imgsrc');
		$.preLoadImages(imageUrl);
		$(this).colorbox({ html: function() {
			return "<img src='" + imageUrl + "' />";
		}});
	});

	// Slide() bug workaround: http://jqueryfordesigners.com/slidedown-animation-jump-revisited/
    // To be moved into a Learnosity wrapper
    var $div = $('.searchform').css('visibility','hidden').show();
    var height = $div.height();
    $div.hide().css({ height : 0 }).css('visibility','visible');

    $('.searchform_show').click(function () {
        if ($div.is(':visible')) {
            $(this).html('Refine Search <span class="arrowdown"></span>');
            $div.animate({ height: 0 }, { duration: 500, complete: function () {
                $div.hide();
            } });
        } else {
            $(this).html('Close Search <span class="arrowup"></span>');
            $div.show().animate({ height : height }, { duration: 500 });
        }	        
        return false;
    });

    /* Hack creating links on Datagrids till we can refactor it's output HTML */
	$('.datagrid tbody tr').click(function(event) {
        var firstCell = $($(this).children('td')[0]);
        var link = firstCell.children('a')[0];
        var checkbox = firstCell.children('input[type="checkbox"]')[0];

        if(link && !$(event.target).is(':checkbox')) {
            window.location.href = link.href;            
        } else if(checkbox && !$(event.target).is(':checkbox')) {
            if ($(checkbox).is(':checked')) {
                $(checkbox).attr('checked', '');
            } else {
                $(checkbox).attr('checked', 'checked');
            }
        }
	});
    
    /* Hack to fire search button even if it's not the first submit in the form */    
    $('.searchform').keypress(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            $('button:last').click();
        }
    });
});

/* Utils */
function getParameterByName(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if(results == null)
		return "";
	else
		return decodeURIComponent(results[1].replace(/\+/g, " "));
}

/* Swf Video (applied to all .swfvideo elements) */		
function loadVideo(elm) {
	var height = elm.children('img').height(),
		width = elm.children('img').width(),
		videoUrl = elm.attr('href'),
		imageUrl = elm.children('img').attr('src'),
		videoID = elm.attr('id');

	if (swfobject.hasFlashPlayerVersion("9.0.0")) {
		var att = { data:'/commonskins/base/swf/player-licensed.swf', width: width, height: height, wmode: "transparent" };
		var par = { flashvars: 'file=' + videoUrl + '&image=' + imageUrl + '&controlbar=over&stretching=fill' };
		var myObject = swfobject.createSWF(att, par, videoID);
	}
}		

function swfViedoInit() {
	var i = 0
	$('.swfvideo').each(function() {
		$(this)[0].id = "swfvideo_" + i++;
		loadVideo($(this));
	});
}

swfobject.addDomLoadEvent(swfViedoInit);

/* Image preloader */
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
