/**
 * Create neccessary variables for scrollers (ajax powered and static)
 */
var current 		= new Array();
var total			= new Array();
var loaded			= new Array();
var static_current 	= new Array();

/**
 * Variable which determine if list of mobile devices is loaded or not
 */
var devices_loaded = false;


/**
 * When DOM is ready, call initialization functions
 */
$(document).ready(function() {
	//Initialize scrollers
	initScrollers();

	//Attach event handlers to window for selecting device
	$("#popupContactClose").click(function(){
	        disablePopUp();
	    });

	    $("#backgroundPopup").click(function(){
	        disablePopUp();
	    });

	    $(document).keypress(function(e){
	    	if(e.keyCode == 27 && $('#devices_container').hasClass('displayed')) {
	    		disablePopUp();
	    	}
	    });
});


function startPlayAudio( urlFlv )
{
	//document.getElementById("audio_player").playAudioFlash(urlFlv);
	var player = document['flash'];
	if(player){
		player.playAudioFlash(urlFlv);
	}else{
		window.status = "no player object found.";
	}
}


/**
 * Function for returning text value for errors used in jquery.formvalidate plugin
 *
 * @param section
 * @param name
 * @return string
 */
function getErrorText(section, name)
{
	return txt[section][name];
}

/**
 * Initialize ajax powered scrollers
 *
 * @return bool false
 */
function initScrollers()
{
	if (typeof sections == 'undefined') {
		return false;
	}
	if (sections.length > 0) {
		for(var i=1; i <= sections.length; i++)
		{
			loaded[i] = new Array;
			loaded[i][1] = true;
			current[i] = 1;
			var target = $('#slider_' + i + ' div.panel');
			total[i] = target.length;
			checkArrows(i, 1);
		}
	}
	return false;
}

function getControllerPrefix()
{
	controllerPrefix = '';

	pathArray = window.location.pathname.split( '/' );

	pathArrayFiltered = Array();

	for ( i = 0; i < pathArray.length; i++ ) {
		if(pathArray[i] != "")
		{
			pathArrayFiltered[pathArrayFiltered.length] = pathArray[i];
		}
	}

	if(pathArrayFiltered.length > 0)
	{
		if (pathArrayFiltered[0].substr(0, 1) == 8) {
			controllerPrefix = pathArrayFiltered[0] + "/";
		}
	}

	return controllerPrefix;
}

/**
 * Reload captcha image
 *
 * @param controller
 * @return false
 */
function reloadCaptcha(controller)
{
	var opts = {
			url: "/"+ getControllerPrefix() + controller + "/reloadcaptcha/",
			data: {},
			type: "POST",
			async:true,
			complete: function(req) {
				if(req.status == 200) {
					if(req.responseText.length > 0) {
						var json = eval('(' + req.responseText+ ')');
						$('#captcha_img').attr('src', json.image);
						$('#cid').val(json.cid);
						return false;
					}
				}
			}
		};
	$.ajax(opts);
	return false;
}

/**
 * Function for displaying select device window and
 * if devices not loaded, load it
 *
 * @return bool false
 */
function loadDevicesPopUp()
{
	if (!devices_loaded) {
		var opts = {
			url: '/devices/ajax/',
			data: { ajax: 1},
			type: "POST",
			async:true,
			timeout:45000,
			error:function (){
				alert('System error!');
				return false;
			},
			beforeSend:function(){

			},
			complete: function(req){
				if(req.status == 200) {
					if(req.responseText.length > 0) {
						$('#devices_container').html(req.responseText);
						return false;
					}
				}
			}
		};
		$.ajax(opts);
//		devices_loaded = true;
	}
	if (!$('#devices_container').hasClass('displayed')) {
		$('#backgroundPopup').css({"opacity":"0.4"});
    	$("#backgroundPopup").fadeIn("fast").css('background','#ff9900');
    	$("#devices_container").fadeIn("fast");

		var windowWidth		= document.documentElement.clientWidth;
	    var windowHeight	= document.documentElement.clientHeight;
	    var pageHeight		= $(document).height();

	    var popupWidth		= 540; //$("#popupContact").width();
	    var popupHeight		= $("#devices_container").height();

	    $('#devices_container').css({
				"position" : "absolute",
	    		"top" : "35px",
	    		"left" : (windowWidth/2)-(popupWidth/2)
	    });
	    $("#backgroundPopup").css({ "height": pageHeight, "width": windowWidth-2 });
	    $('#devices_container').addClass('displayed');
	}
	return false;
}

/**
 * Hide popup window for selecting devices
 *
 * @return bool false
 */
function disablePopUp()
{
    if ($('#devices_container').hasClass('displayed')) {
    	//Reset pagination
    	static_current[1] = 1;
    	$('#staticScroller_1 > a.arrow-left').addClass('disleft');
		$('#staticScroller_1 > a.arrow-right').removeClass('disright');

    	$("#backgroundPopup").fadeOut("normal");
        $("#devices_container").fadeOut("normal");
        $('#devices_container').removeClass('displayed');
    }
    return false;
}

/**
 * Change device manufacturer
 * Function is triggering with onchange event
 * attached on appropriate element
 *
 * @return bool false
 */
function changeDevicesList(id)
{
	var manufacturer_id = $('#manufacturer_id').val();
	var model_type		= $('#model_type').val();
	var opts = {
		url: '/devices/ajax/',
		data: { ajax: 1, manufacturer_id: manufacturer_id, model_type : model_type},
		type: "POST",
		async:true,
		timeout:45000,
		error:function () {
			alert('System error!');
			return false;
		},
		beforeSend:function(){

		},
		complete: function(req){
			if(req.status == 200){
				if(req.responseText.length > 0){
					if (id != undefined && static_current[id] != undefined)
						static_current[id] = 1;

					$('#devices_container').html(req.responseText);
					return false;
				}
			}
		}
	};
	$.ajax(opts);
	return false;
}

/**
 * Call appropriate controller and send selected device_id
 *
 * @param manufacturer_id
 * @return bool false
 */
function changeDevice(manufacturer_id)
{
	var opts = {
		url: '/devices/selectdevice/',
		data: {ajax: 1, manufacturer_id: manufacturer_id},
		type: "POST",
		async:true,
		timeout:45000,
		error:function (){
			alert('System error!');
			return false;
		},
		beforeSend:function(){

		},
		complete: function(req){
			if(req.status == 200){
				if(req.responseText.length > 0) {
					window.location = window.location;
					return false;
				}
			}
		}
	};
	$.ajax(opts);
	return false;
}

/**
 * Scrolling without ajax
 *
 * @param page 				mixed	- desired page (usually prev and next strings but it also can be an integer)
 * @param id				string	- appropriate html element
 * @param target_element	string		integer	-
 * @param pagination		bool	- handle pagination or not
 * @return boolean false
 */
function scrollStatic(direction, id, target_element, pagination)
{
	if (typeof static_current[id] == 'undefined') {
		static_current[id] = 1;
	}

	var target 			= '#staticScroller_' + id;

	if (typeof target_element != 'undefined' && target_element != '') {
		target += ' ' + target_element;
	}
	target += ' .page_container';
	var static_total	= $(target).length;
	var desired			= 1;

	if (parseInt(static_current[id]) < 1 || static_current[id] == undefined) {
		static_current[id] = 1;
	}

	if (direction == "next") {
		 desired = static_current[id] + 1;
	}
	else if (direction == "prev") {
		if (static_current[id] - 1 > 0) {
			desired = static_current[id] - 1;
		}else{
			desired = 1;
		}
	}else{
		desired = parseInt(direction);
	}

	if (parseInt(desired) < 1 || desired > static_total || desired == static_current[id]) {
		return false;
	}

	static_current[id] = desired;

	if (static_current[id] == 1) {
		$('#staticScroller_' + id + ' > a.arrow-left').addClass('disleft');
		$('#staticScroller_' + id + ' > a.arrow-right').removeClass('disright');
	}
	else if (static_current[id] == static_total) {
		$('#staticScroller_' + id + ' > a.arrow-left').removeClass('disleft');
		$('#staticScroller_' + id + ' > a.arrow-right').addClass('disright');
	}else{
		$('#staticScroller_' + id + ' > a.arrow-left').removeClass('disleft');
		$('#staticScroller_' + id + ' > a.arrow-right').removeClass('disright');
	}

	$('#pan_static_' + id + '_' + desired).show();
	$("#scroll_div_static_" + id).scrollTo($('#pan_static_' + id + '_' + desired), 980, {axis:'x'});

	if (pagination) {
		markArrowsStatic(id, desired, static_total);
	}
	return false;
}

/**
 * Mark arrows and change displayed page number
 * for static scrolling
 *
 * @param id		int	Scroll div uniqe id addition
 * @param desired	int	Currently displayed page number
 * @param total		int	Total number of pages for selected scroll
 * @return none
 */
function markArrowsStatic(id, desired, total)
{
	$('#pagination_' + id + ' .current_page').html(desired);

	if (desired == total) {
		$('#pagination_' + id + ' .next_page').addClass('NoActive');
	}
	if (desired < total) {
		$('#pagination_' + id + ' .next_page').removeClass('NoActive');
	}
	if (desired == 1) {
		$('#pagination_' + id + ' .prev_page').addClass('NoActive');
	}
	if (desired > 1 && total > 1) {
		$('#pagination_' + id + ' .prev_page').removeClass('NoActive');
	}
}


function popupErrorForm(){
 //loads popup only if it is disabled
if(popupStatus==0){
 $("#backgroundPopupError").css({
 "opacity": "0.7"
 });
 $("#backgroundPopupError").fadeIn("slow");
 $("#popupContent").fadeIn("slow");
 popupStatus = 1;
 }

}

function disablePopupError(){
//disables popup only if it is enabled
if(popupStatus==1){
$("#backgroundPopupError").fadeOut("slow");
$("#popupContent").fadeOut("slow");
popupStatus = 0;
}
}

function centerPopupError(){
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContent").height();
var popupWidth = $("#popupContent").width();
//centering
$("#popupContent").css({
"position": "absolute",
"top": windowHeight/2-popupHeight/2,
"left": windowWidth/2-popupWidth/2
});
//only need force for IE6

$("#backgroundPopupError").css({
"height": windowHeight
});
}
 $("#popupContactClose").click(function(){
 disablePopupError();
 });
 //Click out event!
 $("#backgroundPopupError").click(function(){
 disablePopupError();
 });

function ContentAlbumsToggle(a)
{
	var ul = $(a).parent().parent().parent().parent();
	var li = $(a).parent().parent().parent();
	var speed = "slow";

	var lis = ul.children();
	for(var i=0; i < lis.length; i++)
	{
		var opened = $(lis[i]).find(".opened");
		var closed = $(lis[i]).find(".closed");

		if(lis[i] == li[0]) {
			opened.slideDown(speed);
			closed.slideUp(speed);
			$(lis[i]).addClass("active");
		} else {
			opened.slideUp(speed);
			closed.slideDown(speed);
			$(lis[i]).removeClass("active");
		}
	}
	return false;
}


//function ContentAlbumsToggle(a)
//{
//	var ul = $(a).parent().parent().parent().parent();
//	var li = $(a).parent().parent().parent();
//	var speed = "slow";
//
//	var tc = li.find(".trackContainer");
//	if(tc) {
//		var empty = tc.attr("empty")=="1"	?	true	:	false;
//		if(empty) {
//			var albumid = tc.attr("albumid");
//			var throb = li.find(".throbber").eq(0);
//			var opts = {
//				url: "./",
//				data: {ajxreq:1, action: "LoadAlbumTracks", id:albumid},
//				beforeSend: function(){
//					throb.show();
//				},
//				complete: function(req){
//					throb.hide();
//					if(req.status == 200){
//						if(req.responseText.length > 0){
//							tc.html(req.responseText);
//							tc.attr("empty",0);
//							ContentAlbumsToggle(a);
//							var tst = $('#alb_' + albumid + ' > .item-list').attr('maxprice');
//							$('#maxPrice_' + albumid).text(tst);
//						}
//					}
//				}
//			};
//			$.ajax(opts);
//		}else{
//			var lis = ul.children();
//			for(var i=0; i<lis.length; i++)
//			{
//				var opened = $(lis[i]).find(".opened");
//				var closed = $(lis[i]).find(".closed");
//
//				if(lis[i]==li[0]) {
//					opened.slideDown(speed);
//					closed.slideUp(speed);
//					$(lis[i]).addClass("active");
//				} else {
//					opened.slideUp(speed);
//					closed.slideDown(speed);
//					$(lis[i]).removeClass("active");
//				}
//			}
//		}
//	}
//}
