var js_spinner   = '<br/><div class="spinner">Зареждане.</div>';
var js_tab_error = "Моля да ни извините, в момента няма достъп до тази страница.";

///////////////////////////
//  GENERAL FUNCTIONALITY
/////////////////////////

$(function() {
     $('body').append('<div id="cms-dialog"><div id="cms-dialog-content"></div></div>');
});

/**
 * Gets the default dialog
 */
function cms_dlg_open(content, title, modal, width) {
    if(modal == undefined) {
        modal = true;
    } else {
        modal = Boolean(modal);
    }

    if(title == undefined) {
        title = '';
    }

    if(width == undefined) {
        width = 350;
    }

    $("#cms-dialog").find('#cms-dialog-content').html(content);

    $("#cms-dialog").dialog('destroy').dialog({
        autoOpen: true,
        modal: modal,
        title: title,
        width: width
    });

    $("#cms-dialog").dialog({autoOpen: false, modal: true});

    $("#cms-dialog").parent().append('<div id="dlg-bottom" class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"></div>');

    // cms_dlg_button_create('Затвори', 'cms_dlg_close()');
}

function cms_dlg_close() {
    $("#cms-dialog").dialog('close');
}

function cms_dlg_get_content() {
    return $("#cms-dialog").find('#cms-dialog-content');
}

function cms_dlg_button_create(title, action) {
    $('#dlg-bottom').append('<a onclick="'+action+'" class="buttonMtel buttonMtelBig" href="#"><span>'+title+'</span></a>');
}

function cms_ajax_message_handler(response, callback_success) {
    var result = false;

    switch(response.code) {
        case 0: // Not authenticated error
            result = true;
            break;
        default:
            cms_alert(response.message);
            break;
    }

    return result;
}
///////////////////////////
// USER MENU
/////////////////////////
$(function() {
	var wdth = $('#header .top-nav .nav .username').width();
	$('#header .top-nav .nav li .usermenu .hdr .mask').css('width',wdth-1);
});


/////////////////////////
// MAIN NAVIGATION
/////////////////////////
$(function() {
	//keep hover state
	$('.submenu').hover(
		function() {
			$(this).parent('li').addClass('hover');
		},
		function() {
			$(this).parent('li').removeClass('hover');
	});
});

/////////////////////////
// DELAY MAIN NAVIGATION
/////////////////////////
$(function() {
  $('.delayed_nav li').hover(
    function(){
      $(this).delay(150).queue(function(next){
        $(this).find('.submenu').fadeIn(100); next();
      });
    }, 
    function(){
      $(this).clearQueue().find('.submenu').hide();
    }
  );
});


/////////////////////////
// THEBOX COLLAPSIBLE
/////////////////////////
$(function() {
  $('.theboxCollapsible .theboxHd').click(function(){
    $(this).closest('.theboxCollapsible').toggleClass('theboxCollapsed');
  });
});

/////////////////////////
// RADIOTABLE TABLE
/////////////////////////
$(function() {
  $('.radioTable :checked').closest('tr').addClass('selected');
   $('.radioTable input').click(function () {
    $(this).closest('table').find('.selected').removeClass('selected');
    $(this).closest('tr').addClass('selected');
  }); 
});

/////////////////////////
// FOOTER MENU
/////////////////////////
$(function() {

	var content_loaded = false;
	
	function init_toolbar() {
		$('.user-menu li').each(function(){
			var hght = $(this).children('.popup').height();
			$(this).children('.popup').css('marginTop', -hght-23);
			var wdth = $(this).width();
			$(this).children('.popup').css('marginLeft', wdth-270);
			$(this).children().children().children('.mask').css('width', wdth+3);
		});
	}
	
	function load_content() {
		if (!content_loaded) {
			content_loaded = true;
			$.post('/public/gettoolbarstats', { },
		        function(data) {
		            if (data.errorCode == 0) {
		            	$("#toolbar_invoice").html(data.response.invoice);
		            	$("#toolbar_bill").html(data.response.bill);
		            	$("#toolbar_sms").html(data.response.sms);
		            	$("#toolbar_club").html(data.response.club);
		            	init_toolbar();
		            } else {
		            	$("#toolbar_invoice").html(data.errorMessage);
		            	$("#toolbar_bill").html(data.errorMessage);
		            	$("#toolbar_sms").html(data.errorMessage);
		            	$("#toolbar_club").html(data.errorMessage);
		            }
		        },'json'
		    );
		}
	}
	
	init_toolbar();
	$('.others li').each(function(){
		var hght = $(this).children('.popup').height();
		$(this).children('.popup').css('marginTop', -hght-23);
	});
	$('.footer-bar .others li a').not('.popup a').click(function(ev){
		ev.preventDefault();
		if(!$(this).parent().hasClass('opened')) $('.footer-bar li').removeClass('opened'); //close all opened tips
		$(this).parent().toggleClass('opened');
	});
	$('.footer-bar .user-menu li a.logged').not('.popup a').click(function(ev){
		ev.preventDefault();
		load_content();
		if(!$(this).parent().hasClass('opened')) $('.footer-bar li').removeClass('opened'); //close all opened tips
		$(this).parent().toggleClass('opened');
	});
	$('.footer-bar .popup .close').click(function(ev){
		ev.preventDefault();
		$(this).closest('.popup').parent().removeClass('opened');
	});
});


/////////////////////////
// SECTION
/////////////////////////
//$(function() {  
//	$('.section .switch, .section .switch ~ h2').addClass('clickable').click(function(ev){
//		$(this).closest('.section').toggleClass('closed');
//		ev.preventDefault();
//	});	
//	$('.sections .section:not(:first)').addClass('closed')
//});
$(function() {
	//$('.section .switch').closest('.section').addClass('clickable');
	$('.section .switch').click(function(ev) {
		var ix = $('.section .switch').index(this);
		ev.preventDefault();

		$('.section').eq(ix).toggleClass('closed');

	});


	//$('.sections .section:not(:first)').addClass('closed')
});


/////////////////////////
// TABS
/////////////////////////
$(function(){
  
  if ($('.uitabs').length > 0) {
    $('.uitabs').tabs({cache:1});
  }

  //Табове - ако не са на един ред слага клас
  $(".tabs li").each(function() {
    if ($(this).height() > 35) {
      $(this).addClass('dva-reda');
    }
  });
});

/////////////////////////
// Help Bubbles
/////////////////////////
$(function(){
 $('.bubble').live( 'hover' , function(){
   $(this).find('.bubbleContent').toggle();
 });
});

/////////////////////////
// Catalog
/////////////////////////
$(function(){
 $(".catalog .item:nth-child(3n)").addClass('lastUnit');
 $(".cat2 .item:nth-child(2n)").addClass('lastUnit');
});

/////////////////////////
// Search Box Label
//      http://trevordavis.net/blog/jquery-inline-form-labels
/////////////////////////
$(document).ready(function() {
	$('input[title]').each(function() {
		if($(this).val() === '') {
			$(this).val($(this).attr('title'));	
		}
		
		$(this).focus(function() {
			if($(this).val() == $(this).attr('title')) {
				$(this).val('').addClass('focused');	
			}
		});
		$(this).blur(function() {
			if($(this).val() === '') {
				$(this).val($(this).attr('title')).removeClass('focused');	
			}
		});
	});
});


/////////////////////////
// THE BOX
/////////////////////////
$(document).ready(function() {
	$('.thebox').prepend('<b class="theboxTop"><b class="theboxTl"></b><b class="theboxTr"></b></b>');
	$('.thebox').append('<b class="theboxBottom"><b class="theboxBl"></b><b class="theboxBr"></b></b>')
});

/////////////////////////
// FAQ LIST
/////////////////////////
$(document).ready(function() {
	$('.faqItem .toggle').click(function(){
		if(!$(this).closest('.faqItem').hasClass('opened'))
		{
			var questId = $(this).next('.thebox').find(':radio').attr('name');
			questId = questId.substring(9); //question_<id>
			_ajaxIncreaseCounter(questId);
		}
	  $(this).closest('.faqItem').toggleClass('opened');
	  $(this).next('.thebox').toggle();
	  $(this).closest('.faqItem').next('hr').toggle();
	  return false;
	})
});

/////////////////////////
// DEACTIVATE PROFILE POPUP DIALOG
/////////////////////////
$(function() {
	$('.toggle_deactivation_popup').click(function(e){
	  $('#vnimanie').toggle();
	  e.preventDefault();
	});
});

/////////////////////////
// COMPARE BOX
/////////////////////////
$(function() {  
 
  if ($('#compareBox').length>0) {  // if compareBox exists on the page
  
    var boxOffset = $("#compareBox").offset().top; // count pixels from document top to compareBox top
    var navBottomOffset = $(".page-nav").offset().top + $(".page-nav").height(); // count pixels from document top to nav bottom    
    
    if (navBottomOffset - boxOffset > 0){ // find if compareBox is on top of Nav and move it bellow
      $('#compareBox').css('top', navBottomOffset + 20);
      var boxOffset = $("#compareBox").offset().top - 6; // recalculate boxOffset and subtract 6px because of margin-top(?)
    };
    
    $('.catalog :checkbox').click(function(){ // show the compareBox when a checkbox is clicked
      $('#compareBox').css('visibility','visible').hide().fadeIn(400);      
    })
  
    $(window).scroll(function(){ // when scrolling...
      var y = $(window).scrollTop(); // count how many pixels have been scrolled
      if (y > boxOffset) { // if scrolled pixels are more than the pixels from document top to compareBox top
        $('#compareBox').addClass('fixed');
      } else {
        $('#compareBox').removeClass('fixed');
      }
      
    });
    
  };

});

/////////////////////////
// SHOW/HIDE CLOSE BUTTON in .close_me div
/////////////////////////

$(function(){
  $('.close_me').hover(function(){
    $('.close_icon', this).toggle();
  })
});

/////////////////////////
// REGISTRATION FORM -- ADD MAIL
/////////////////////////
$(function() {
  $('.addMail').click(function(e){
    $(this).closest('.mail_additional').next().clone().appendTo('#additional_mails').show();
    e.preventDefault();
  });
  $('.removeMail').live('click', function(e){
    $(this).closest('.mail_additional').remove();
    e.preventDefault();
  })
});


/////////////////////////
// CAROUSEL - MY CUSTOM
/////////////////////////

$(function(){   
    
  /* ако има карусел в страницата */
  if ($('.caru').length>0){
    
    /* за всеки карусел */
    $('.caru').each(function(){
      
      /* виж колко Items сме написали, че са видими */
      //var caruVisibleItems = $(this).attr('data-caru-visible');
      var caruVisibleItems = 3;
	  
      /* сложи класове на първия и последния видим Item */
      $('.caruItem:first', this).addClass('caruFirstVisible');
      $('.caruItem:lt(' + caruVisibleItems + '):last', this).addClass('caruLastVisible');
      
    });
    
    /* скрий Prev линк */
    $('.caruPrev', this).addClass('caruNavDisabled');
    
    /* като кликнеш на Next */
    $('.caruNext').click(function(e){      
      
      /* виж колко e широк първият видим Item */
      var caruFirstVisibleWidth = $(this).closest('.caru').find('.caruFirstVisible').width();
      
      /* анимирай с толкова пиксела .caruWrap наляво */
      $(this).closest('.caru').find('.caruWrap').animate({marginLeft: '-=' + caruFirstVisibleWidth}, 300, 'linear', function(){
        
        /* като свърши анимацията.. */
        
        /* не започвай чакащи анимации (ако междувремено е кликано на Next) */
        $(this).stop(true); 
        
        /* махни класовете на първия и последния видим Item и ги премести на следващите */
        $('.caruFirstVisible', this).removeClass('caruFirstVisible').next().addClass('caruFirstVisible');
        $('.caruLastVisible', this).removeClass('caruLastVisible').next().addClass('caruLastVisible');
        
        /* скрий Next линка, ако си стигнал до края */
        if($('.caruLastVisible', this).is(':last-child')){
          $(this).closest('.caru').find('.caruNext').toggleClass('caruNavDisabled');
        } ;
        
        /* покажи Prev линка, ако е скрит */
        if($(this).closest('.caru').find('.caruPrev').is('.caruNavDisabled')){          
          $(this).closest('.caru').find('.caruPrev').removeClass('caruNavDisabled');
        };
        
      });        
      e.preventDefault();
      
    });
    
    /* като кликнеш на Prev */
    $('.caruPrev').click(function(e){
      
      /* виж колко e широк елементът преди първия видим Item */
      var caruPrevWidth = $(this).closest('.caru').find('.caruFirstVisible').prev().width();
      
      /* анимирай с толкова пиксела .caruWrap надясно */
      $(this).closest('.caru').find('.caruWrap').animate({marginLeft: '+=' + caruPrevWidth}, 300, 'linear', function(){
        
        /* като свърши анимацията.. */
        
        /* не започвай чакащи анимации (ако междувремено е кликано на Prev) */
        $(this).stop(true);
        
        /* махни класовете на първия и последния видим Item и ги премести на предишните */
        $('.caruFirstVisible', this).removeClass('caruFirstVisible').prev().addClass('caruFirstVisible');
        $('.caruLastVisible', this).removeClass('caruLastVisible').prev().addClass('caruLastVisible');
        
        /* скрий Prev линка, ако си стигнал до края */
        if($('.caruFirstVisible', this).is(':first-child')){
          $(this).closest('.caru').find('.caruPrev').toggleClass('caruNavDisabled');
        };
        
        /* покажи Next линка, ако е скрит */
        if($(this).closest('.caru').find('.caruNext').is('.caruNavDisabled')){          
          $(this).closest('.caru').find('.caruNext').removeClass('caruNavDisabled');
        };
        
      });
      e.preventDefault();
      
    });
  
  };
  	
});

/////////////////////////////////////////////////////////////
// DYNAMICALLY LOADING CHILDREN OF NON-CLICKABLE MENU ITEMS
/////////////////////////////////////////////////////////////

var loadedNodes = new Array();

function toggleMenu(navigationId, linkElement) {

	//check if node's children are already loaded
	if ($.inArray(navigationId, loadedNodes) == -1) {
		$.post('/public/loadmenu', {navigation_id: navigationId},
		    function(data) {
		        if (data.errorCode == 0) {
		          	var element = $(linkElement);
		           	element.parent().append(data.response);
		          	loadedNodes.push(navigationId);
		        }
		    },'json'
		);
	}
}

$(function(){
	var cnt = $( '.uitabs' ).length;
	if( cnt > 0 ){

		$(".uitabs li").each(function() {
			if ($(this).height() > 35) {
			  $(this).addClass('dva-reda');
			}
		});

		$( '.uitabs' ).tabs({
			spinner: js_spinner,
			cache:true,
			ajaxOptions: {
			error: function( xhr, status, index, anchor ) {
				$( anchor.hash ).html( js_tab_error );
			}
			},
			load: function(event, ui) {
				revive( '.uitabs');
			}
		});

		$(".uitabs a").click(function(){
			var custom = $(this).attr('rel');
			if( typeof(custom) !== 'undefined'  &&  custom.length > 0 ){
				$(".bodyBgrInner").css( { backgroundImage : 'url('+custom+')'});
			}
		  });
	}
});

function revive( myclass ) {

	$(myclass+' table:not(.ajaxed) tr:last-child').addClass('last');
	$(myclass+' .standard:not(.ajaxed) colgroup').prepend('<col style="width:8px;"></col>');
	$(myclass+' .standard:not(.ajaxed) colgroup').append('<col style="width:8px; "></col>');
	$(myclass+' .standard:not(.ajaxed) tbody tr:not(.head)').prepend('<td class="first">&nbsp;</td>');
	$(myclass+' .standard:not(.ajaxed) tbody tr:not(.head)').append('<td class="last">&nbsp;</td>');
	$(myclass+' .standard:not(.ajaxed) tbody tr.head th').removeClass('first');
	$(myclass+' .standard:not(.ajaxed) tbody tr.head').prepend('<th class="first" >&nbsp;</th>');
	$(myclass+' .standard:not(.ajaxed) tbody tr.head').append('<th class="last">&nbsp;</th>');
	$(myclass+' .collapsible:not(.ajaxed) th.last').html( '');
	$(myclass+' .collapsible:not(.ajaxed) th.last').append('<a href="#" class="switch"><span>Open/Close</span></a>');

	if( $( 'table:not(.ajaxed) td').size() > 0  ){
		$( myclass+' td').each(function(i , val){
			var cell_v = $( myclass+' td').eq(i).html();
			if( jQuery.trim(cell_v) == '' )
				$( myclass+' td').eq(i).prepend(' &nbsp; ');
		});
	}

	if( $( 'table:not(.ajaxed) th').size() > 0  ){
		$( myclass+' th').each(function(i , val){
			var cell_v = $( myclass+' th').eq(i).html();
			if( jQuery.trim(cell_v) == '' )
				$( myclass+' th').eq(i).prepend('&nbsp;');
		});
	}

	$('td.first , td.last').css( {'padding' : '0px !important'});
	$('th.first , th.last').css( {'padding' : '0px !important'});


	if( $( '#ajaxrebuild:not(.ajaxed)  span').size() > 0  ){
		$( myclass+' #ajaxrebuild:not(.ajaxed)  span').each(function(i , val) {

			if( !$(this).parent().hasClass('ajaxed'))
				$(this).parent().addClass('ajaxed');

			var script_name = $(this).attr('rel');
			
			if( script_name.indexOf( 'http://maps.google') < 0  && script_name.indexOf( 'https://maps.google') < 0){
				var th = document.getElementsByTagName('body')[0];
				var s = document.createElement('script');
				s.setAttribute('type','text/javascript');
				s.setAttribute('src',$(this).attr('rel'));
				th.appendChild(s);
			}
		});
	}

	size =$(myclass+' .closed tr').eq(0).children().size();
	var cSpan = 0;
	for( var k =0; k<size; k++){
		cSpan +=$(myclass+' .closed tr').eq(0).children().eq(k).attr('colspan');
	}

	$( myclass+' table:not(.ajaxed) tbody .switch').closest('tr').addClass('clickable');

	$( myclass+' .collapsible:not(.ajaxed) .switch').closest('tr').click(function(ev) {
		ev.preventDefault();
		$(this).closest('tbody').toggleClass('closed');
	});


	// patch for preventing closed harmonic to absolutly closed ?!
	if( $(myclass+' .collapsible:not(.ajaxed) tbody').hasClass('closed') ){
		$(myclass+' .collapsible:not(.ajaxed) .switch').not(':first').closest('tbody').append('<tr class="vSpace"><td colspan="'+cSpan+'"></td></tr>');

	}else{
		$(myclass+' .collapsible:not(.ajaxed) .switch').not(':first').closest('tbody').addClass('closed');
		$(myclass+' .collapsible:not(.ajaxed) .closed').append('<tr class="vSpace"><td colspan="'+cSpan+'"></td></tr>');
	}

	$( myclass+' .collapsible:not(.ajaxed) tbody:not(.closed) .switch').closest('tr').toggle(function() {
			$(this).closest('tbody').append('<tr class="vSpace"><td colspan="'+cSpan+'"></td></tr>');
		},function() {
			$(this).closest('tbody').children('.vSpace').remove();
	});

	$( myclass+' .collapsible:not(.ajaxed) tbody.closed .switch').closest('tr').toggle(function() {
			$(this).closest('tbody').children('.vSpace').remove();
		},function() {
			$(this).closest('tbody').append('<tr class="vSpace"><td colspan="'+cSpan+'"></td></tr>');
	});


   	if ($('.caru:not(.ajaxed)').length>0){
		$('.caru:not(.ajaxed)').each(function(){
		  var caruVisibleItems = 3;

		  $('.caruItem:lt(' + caruVisibleItems + '):first', this).addClass('caruFirstVisible');
		  $('.caruItem:lt(' + caruVisibleItems + '):last', this).addClass('caruLastVisible');
		});
		$('.caruPrev', this).addClass('caruNavDisabled');
		$('.caruPrev', this).addClass('ajaxed');
	}

	$(myclass+' .standard:not(.ajaxed)').addClass('ajaxed');
	var cnt = $( myclass+' .extab' ).length;
	if( cnt > 0 ){

		$( myclass+' .extab:not(.ajaxed)' ).each(function(i , val) {
			 $( myclass+' .extab' ).eq(i).addClass('ajaxed');
			 $( myclass+' .extab' ).eq(i).html(
				$.ajax(
				{
					url      :  $( myclass+' .extab' ).eq(i).attr( 'rel'),
					dataType : 'html',
					async    : false
			}).responseText);
		});
		revive( '.extab');

	}

}

$(".flashlink").live( 'click' ,function(){

	if( $('#flashtmpbox').length == 0  ){
		$('body').append('<div id="flashtmpbox"></div>');
	}

	$("#flashtmpbox").dialog({autoOpen: false, modal: true , position: 'center' , width: 800 , height:600 });

	ix = $(".flashlink").index(this);
	var flash = $( '.flashlink' ).eq(ix).attr( 'rel');

	if( $( '.flashlink' ).eq(ix).hasClass('inbox') ){
		$("#flashtmpbox").html(" ");
		var flash_title = $( '.flashlink' ).eq(ix).text();
		var lastpos = flash.lastIndexOf('.') + 1;
		if( flash.substr( lastpos , 3 ) != 'flv' ){
			flash_tpl = '<div style="text-align:center; margin:auto;"><div id="flashme" style="margin:auto; float:none;"></div></div>'+
					'<script type="text/javascript">'+
					'var so = new SWFObject("'+flash+'", "movie", "700", "550", "9", "#ffffff");'+
					'so.addParam("salign", "t");'+
					'so.addParam("allowFullScreen", "true");'+
					'so.addParam("wmode", "transparent");'+
					'so.addParam("menu", "false");'+
					'so.write("flashme");<\/script>';
		} else{
			flash_tpl = '<div style="text-align:center; margin:auto;"><div id="flashme" style="margin:auto; float:none;"></div></div>'+
					'<script type="text/javascript">'+
					'var so = new SWFObject("http://www.mtel.bg/players/flv/player.swf" , "movie", "700", "550", "9", "#ffffff");'+
					'so.addParam("salign", "t");'+
					'so.addParam("allowFullScreen", "true");'+
					'so.addParam("wmode", "transparent");'+
					'so.addParam("menu", "false");'+
					'so.addParam("flashvars", "file='+flash+'&screencolor=FFFFFF");'+
					'so.write("flashme");<\/script>';
		}

/*var so = new SWFObject("http://www.mtel.bg/players/flv/player.swf", "movie", "510", "373", "9", "#ffffff");
 so.addParam("salign", "t");
 so.addParam("wmode", "transparent");
 so.addParam("allowFullScreen", "true");
 so.addParam("menu", "false");
;
 so.write("m-tel_player");*/


		$("#flashtmpbox").html( flash_tpl );
		$("#flashtmpbox").dialog('option', 'title', flash_title );
		$("#flashtmpbox").dialog('open');
	}else{
		var page = flash;
		var windowprops = "width=700,height=550,location=no,menubar=no,toolbar=no,scrollbars=no,resizable=no";
		newWindow = window.open(page,'PopupName',windowprops);
	}
});

var wins_pop = null;
/* window popup functions */
function pop_window( url , params , winid )
{
    wins_pop = window.open( url , winid, params );

    if( typeof(wins_pop) === 'object'  )
	    wins_pop.focus();
    return false;
}

function OpenContact()
{
    var tmp_url = 'kontakti?show=popup';
    var params  = 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,status=0,width=500,height=575';
    var winid   = 'ContactUs';
    pop_window( tmp_url , params , winid );
}

var activereception_link = 'https://activereception.com/Chat/Client_page/Active_reception_link.php?&action=chat&generated_code_id=10&web_id=jVpX5wtR';

function activereception_ShowWindow(newURL,x,y,w,h) {
	width= 435;
	height = 480;
	try {
		activereception_newWindow = window.open(newURL, 'name_h9zArPke', 'height='+height+',width='+width+',left='+x+',top='+y+',channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=1,status=0,toolbar=0', 'activereception_myWindow');
		activereception_newWindow.focus();
	} catch(err) {}
}

