function mycarousel_initCallback(carousel) {
  $('.slider-nav a', carousel.container).live('click', function() {
    carousel.scroll($.jcarousel.intval($(this).text()));
    return false;
  });
};
	
function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
  $('.slider-nav a', carousel.container).removeClass('active');
  $('.slider-nav a', carousel.container).eq(idx-1).addClass('active');
}
	
$(function(){

  $(".slider").jcarousel({
    scroll: 1,
    wrap: 'both',
    auto: 3,
    itemVisibleInCallback: {
      onBeforeAnimation: function(carousel, item, idx, state) {
        carousel.options.animation = 0;
        carousel.container.find("ul li img").css({
          opacity:0
        });
        $(item).find("img").animate({
          opacity:1
        }, 800, function(){
          carousel.container.find(".slider ul li img").css({
            opacity:1
          });
        });
      },
      onAfterAnimation:  function(carousel, item, idx, state) {
        carousel.options.animation = "fast";
      }
    },
    itemFirstInCallback: mycarousel_itemFirstInCallback,
    initCallback: mycarousel_initCallback,
    buttonNextHTML: null,
    buttonPrevHTML: null
  });

  $(".slider-1").jcarousel({
    scroll: 0,
    wrap: 'both',
    auto: 3,
    itemVisibleInCallback: {
      onBeforeAnimation: function(carousel, item, idx, state) {
        carousel.options.animation = 0;
        carousel.container.find("ul li img").css({
          opacity:0
        });
        $(item).find("img").animate({
          opacity:1
        }, 800, function(){
          carousel.container.find(".slider-1 ul li img").css({
            opacity:1
          });
        });
      },
      onAfterAnimation:  function(carousel, item, idx, state) {
        carousel.options.animation = "fast";
      }
    },
    itemFirstInCallback: mycarousel_itemFirstInCallback,
    initCallback: mycarousel_initCallback,
    buttonNextHTML: null,
    buttonPrevHTML: null
  });

  $("a.video-loader, a.info-ico").colorbox({width: '630px', height: '480px'});
  $(".sign_in_link").colorbox({
    inline:true,
    href:"#signin_forms"
  });
  var data = $.parseJSON($("#seo_keywords").val());
   
  $("#search_box").autocomplete(data, {
    minChars: 2,
    matchContains: "word",
    matchCase: false,
    autoFill: false,
    width: '241px',
    formatItem: function(row, i, max) {
      return "<a href="+ row.url +">"+ row.product + "</a>";
    },
    formatMatch: function(row, i, max) {
      return row.keyword;
    },
    formatResult: function(row) {
      return row.product;
    }
     
  }).result(function(event, item) {
    location.href = item.url;
  });
	
  $("#navigation ul li").hover(function() {
    if( $(this).find(".dd").length && !($(this).find(".dd").is(':animated')))
    {
      $(this).find(".dd").slideDown('fast');
      $(this).addClass('hovered');
    }
			
  }, function(e) {
    var dis = $(this);
    $(this).find(".dd").slideUp('fast', function(){
      dis.removeClass('hovered');
    });
  });
	
  $('ul.dd-list li').hover(function(){
    $(this).addClass('hover');
  },function(){
    $(this).removeClass('hover');
  });
	
  $('ul.dd-list li').click(function(){
    var href = $(this).find('a').attr('href');
    window.location.href = href;
    return false;
  });
	
  $('.search-form span.field input').focus(function () {
    if ($(this).val() == $(this).attr('title')) {
      $(this).val('');
    }
  });
	
  $('.search-form span.field input').blur(function () {
    if ($(this).val() == '') {
      $(this).val($(this).attr('title'));
    }
  });
	
  $('.hero-panel ul li').hover(function(){
    $('.default-title').hide();
    $('.category-heading').hide();
    var idx = $(this).index();
    $('.category-heading:eq('+idx+')').show();
		
    /* makese all blocks fadeout */
    $('.hero-panel ul li').each(function(){
      var coords = 0
      if($.browser.msie){
        var x = $(this).find('span.ico').css("background-position-x").replace("px", "");
        if($(this).parents('.min-panel').length){
          var y = 75;
        } else {
          var y = 94;
        }
				
				
      } else {
        coords = $(this).find('span.ico').css("background-position").split(" ");
        var x = coords[0].replace("px", "");
        if($(this).parents('.min-panel').length){
          var y = 75;
        } else {
          var y = 94;
        }
      }
			
      $(this).find('span.ico').css({
        backgroundPosition: x+"px -"+y+"px"
      });
    });
		
    /* makes the current block to shine :) */
    $(this).addClass('hover');
    if($.browser.msie){
      var x = $(this).find('span.ico').css("background-position-x").replace("px", "");
      if($(this).parents('.min-panel').length){
        var y = 150;
      } else {
        var y = 188;
      }
			
    } else {
      coords = $(this).find('span.ico').css("background-position").split(" ");
      var x = coords[0].replace("px", "");
      if($(this).parents('.min-panel').length){
        var y = 150;
      } else {
        var y = 188;
      }
    }
		
    $(this).find('span.ico').css({
      backgroundPosition: x+"px -"+y+"px"
    });
		
  },function(){
    /* get back the default coordinates of the image */
    $('.hero-panel ul li').each(function(){
      var coords = 0
      if($.browser.msie){
        var x = $(this).find('span.ico').css("background-position-x").replace("px", "");
        var y = 0;
				
      } else {
        coords = $(this).find('span.ico').css("background-position").split(" ");
        var x = coords[0].replace("px", "");
        var y = 0;
      }
			
      $(this).find('span.ico').css({
        backgroundPosition: x+"px -"+y+"px"
      });
    });
		
    $(this).removeClass('hover');
		
    var coords = $(this).find('span.ico').css("background-position").split(" ");
    var x = coords[0].replace("px", "");
    var y = 0;
    $(this).find('span.ico').css({
      backgroundPosition: x+"px -"+y+"px"
    });
		
    $('.category-heading').hide();
    $('.default-title').show();
  });
	
  $('.compare-table table tr:even').addClass('darker');
	
  $('.rel').css('height', $('.loader').height()+'px');
	
  $('.subnav a').click(function() {
    var direction = 0;
    if ($(this).attr('custom_attr')  == "noajax") {
      return true;
    }
	//For now return true for all pages. The side loading is causing a bit of an issue with prettyphoto based popups.
	return true;
	
    if($(this).parents('li').index() < $(this).parents('ul').find('li.active').index()){
      direction = 1;
    }
    if($(this).parents('li').index() == $(this).parents('ul').find('li.active').index()){
      direction = 2;
    }
		
    $('.subnav li').removeClass('active');
    $(this).parents('li').addClass('active');
    var href = $(this).attr('href');
		
    $(".slider").jcarousel({
      auto:0
    });
		
    if(direction==2){
			
    } else {
      loadPage(href, direction);
    }
		
    return false;
  });
	
  if($.browser.msie && $.browser.version==6)
  {
    DD_belatedPNG.fix('.logo-holder, h1#logo a, .search-form span.field, .search-form input.search-submit, .search-dd-t, .search-dd-c, .search-dd-b, #navigation ul li.active a, #navigation ul li.active a span, #navigation ul li.hovered a, .home-header .shell, .home-header ul li span.ico, .logos img, .socials a, .dd-t, .dd-b, .dd-c, .landing-cnt h2.logo, .slider, .slider-1, table img, .blockquote span.br-quotes, #footer .main-col ul li ');
  }
	
  extraLoad();

  /* product-list checkboxes */
	
  $('.product-list td').hover(function(){
    $(this).parents('tr').addClass('hover');
  },function(){
    $(this).parents('tr').removeClass('hover');
  });
	
  $('.product-list tr').each(function(){
    if($(this).find('input.checkbox').is(':checked')){
      $(this).addClass('selected');
    }

  })
        
  $('.product-list .add-link').click(function(){
    var current = '.product-list span.check';
    if($(this).parents('tr').find('input.checkbox').is(':checked')){
      $(this).parents('tr').find('input.checkbox').attr('checked', false);
      $(this).parents('tr').removeClass('selected');
    } else {
      $(this).parents('tr').find('input.checkbox').attr('checked', true);
      $(this).parents('tr').addClass('selected');
    }
    return false;
  });
	
  /* custom select box & calculating */
  if((".custom-select").length > 0){
    $('.custom-select').selectbox();
      
    $('.custom-select select').change(function(){
      setProductValues(per_user_pricing);
      $('#plan').val($(".custom-select select").val());
      totalCalc(per_user_pricing);
    });
    
  }
    
  if($("#per_user_pricing").length > 0){
    var per_user_pricing = $.parseJSON($('#per_user_pricing').val());
    setProductValues(per_user_pricing, true);
  }
	
  $('a.scroll').click(function(){
    $.scrollTo($('.product-list'), 1000, {
      offset: -10
    });
    return false;
  });
	
	
  /* calculating the total sum */
  if($('#per_user_pricing').length > 0)
    totalCalc(per_user_pricing);

  $('.product-list tr td .add-link').click(function(){
    totalCalc(per_user_pricing);
  });

    
  // This is called when 1 checkbox is clicked
  $('.product-list span.check').click(function(){
    var $checkbox = $(this).parents('td').find('input.checkbox');
    if(!$checkbox.attr('disabled')){
      if($checkbox.is(':checked')){
        $checkbox.attr('checked', false);
        $(this).parents('tr').removeClass('selected');
        uncheckFree();
      } else {
        $checkbox.attr('checked', true);
        $(this).parents('tr').addClass('selected');
      }
      var checked_boxes = $("#products_list input:checked");
      if(checked_boxes.length == 4){
        $("#dollar_one_product").val($checkbox.val());
        $checkbox.parent().parent().find('h3 em').html('1.00');
      }
      totalCalc(per_user_pricing);
    }
  });
	

	
  /* sigup form js */
  $('.acnt-form input').focus(function(){
    if($(this).attr("id") == "ccPwd"){
      value = $(this).val();
      if(value == 'CVV')
        $(this).val("");
    }
    $(this).parents('.row').addClass('focus');
  });
	
  $('.acnt-form input').blur(function(){
    if($(this).attr("id") == "ccPwd"){
      value = $(this).val();
      if(value == '')
        $(this).val("CVV");
    }
    $(this).parents('.row').removeClass('focus');
  });
	
//	reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	
//	$('.acnt-form input.acnt-submit').click(function(){
//		var empty = 0;
//		$('.acnt-form input.required').each(function(){
//			if($(this).val()==""){
//				empty = 1;
//			}
//		});
//
//		var mail = $('input#mail-field').val();
//
//		if(reg.test(mail) == false){
//			$('p.error-field').text('Not a valid e-mail').slideDown();
//			return false;
//		}
//		else if(empty){
//			$('p.error-field').text('Fill the required fields').slideDown();
//			return false;
//		} else {
//			return true;
//		}
	
});

$(window).load(function(){
  $('.rel').css('height', $('.loader').height()+'px');
});

function setProductValues(per_user_pricing, reload){
  $.each(["mango_talk", "mango_docs", "mango_tasks", "mango_projects", "mango_ideas", "mango_events", "mango_suite"],    function(index, value){
    //if($("#current_product").val() == value){
    //  $("#"+value+"_guests").text(per_user_pricing['iron'][value]["guests"]);
    //  $("#"+value+"_storage").text(per_user_pricing['iron'][value]["storage"]);
    //  $("#"+value+"_feature").text(per_user_pricing['iron'][value]["feature"]);
    //  $("#"+value+"_extra_users").text(per_user_pricing['iron'][value]["price"]);
    //}
    if(($("#current_product").val() == "mango_suite") && ($("#custom").length == 0) && reload != undefined){
      if(index == 3)
        $("#"+value).text("1.00");
      else if(index > 3 && index <= 5)
        $("#"+value).text("0.00");
      else
        $("#"+value).text(parseFloat(per_user_pricing['iron'][value]["price"]).toFixed(2));
    }else{
      $("#"+value).text(parseFloat(per_user_pricing['iron'][value]["price"]).toFixed(2));
    }
  });
}

function totalCalc(prices){
  var sum = 0.0;
  var val = "";
  var num = 0;
  var calculate = true;
  $('.product-list tr.selected em').each(function(){
    val = $(this).html();
    if(val == "0.00")
      calculate = false
    sum += parseFloat(val);
    num ++;
  });
  if(calculate){
    if(num == 3){
      setProductValues(prices);
      $('#total-sum').text(sum.toFixed(2));
      makeRemOneDollar();
    }else if(num >= 4){
      var price = prices['iron']["mango_suite"]["price"];
      var suite_sum = parseFloat(price);
      $("#total-sum").text(suite_sum.toFixed(2));
      checkAll();
    }else{
      setProductValues(prices);
      $('#total-sum').text(sum.toFixed(2));
    }
  }
}

function tabsLoad(href, link) {
  $('.tab').addClass('old-cnt');
  $.ajax({
    url: href,
    type: "GET",
    success: function(page){

      $(page).find(".tab").appendTo('.content').addClass('new-cnt').hide();
			
      $('.old-cnt').fadeOut(function(){
        $(this).remove()
        $('.side-navigation ul li').removeClass('active');
        link.parents('li').addClass('active');
        $('.new-cnt').show();
        $('.rel').css('height', $('.loader').height()+'px');
      });
    }
  });
}

function loadPage(href, direction) {
  $('body').append('<div class="loaded-page" style="position: absolute; top: -10000px; left: -10000px; width: '+$(window).width()+'px;">'); //900px
  $.ajax({
    url: href,
    type: "GET",
    success: function(page){
      $(page).find(".loader").appendTo('.loaded-page');
			
      if(direction){
        $('.rel').append('<div class="loader" style="width: '+$(window).width()+'px; position: absolute; right: '+$(window).width()+'px; top: 0;"></div>'); //add div .new-content in the right
        $('.rel .loader:eq(1)').append($('.loaded-page .loader').html());
        $('.loader:eq(0)').css({
          'position' : 'absolute',
          'top' : 0,
          'left': 'auto',
          'right' : 0
        }).animate({
          'right' : '-'+$(window).width()+'px'
        });
        $('.loader:eq(1)').animate({
          'right' : 0
        }, {
          complete: function() {
            $('.loader:eq(0), .loaded-page').remove();
            $('.rel').css('height', $('.loader').height()+'px');
          }
        });
      } else {
        $('.rel').append('<div class="loader" style="width: '+$(window).width()+'px; position: absolute; left: '+$(window).width()+'px; top: 0;"></div>'); //add div .new-content in the right

        $('.rel .loader:eq(1)').append($('.loaded-page .loader').html());
        $('.loader:eq(0)').css({
          'position' : 'absolute',
          'top' : 0,
          'left' : 0
        }).animate({
          'left' : '-'+$(window).width()+'px'
        });
        $('.loader:eq(1)').animate({
          'left' : 0
        }, {
          complete: function() {
            $('.loader:eq(0), .loaded-page').remove();
            $('.rel').css('height', $('.loader').height()+'px');
          }
        });
      }
	
      extraLoad();
				
    }
  });
}

function extraLoad(){

  if(('#nivo-slider').length > 0){
    $('#nivo-slider').nivoSlider({
      effect: 'sliceUpDownLeft',
      pauseTime: 6000
    });
  }
	  
  $('.side-navigation ul li a').click(function(){
    var href = $(this).attr('href');
    tabsLoad(href, $(this));
    return false;
  });
	
  //createCarousel();

  $("a.video-loader").colorbox();
	
  if($.browser.msie && $.browser.version==6)
  {
    DD_belatedPNG.fix('.side-navigation ul li span, .work-with-us img, .side-navigation ul li span, #footer .main-col ul li a img');
  }
}

function checkAll(){
  var free_products = []
  $.each($('.product-list tr span.check'), function(index, value){
    if(!($(value).next().attr('checked'))){
      $(value).parent().parent().find('h3 em').html('0.00');
      $(value).click();
      $(value).next().attr('disabled', true);
      free_products.push($(value).next().val());
    }
    if(free_products != "")
      $("#free_products").val(free_products.join(','));
  });
}

function uncheckFree(){
  $.each($('.product-list tr span.check'), function(index, value){
    if(($(value).next().attr('disabled'))){
      $(value).next().attr('disabled', false);
      $(value).click();
    }
    $("#free_products").val("");
    $("#dollar_one_product").val("");
  });
}

function makeRemOneDollar(){
  $.each($('.product-list tr span.check'), function(index, value){
    if(!($(value).next().attr('checked'))){
      $(value).parent().parent().find('h3 em').html("1.00");
    }
  });
}

