var Main = Class.$extend({
  newsListExpandDelay: 1000,
  formsWithStepsPageWidth: new Array(),
  formsWithStepsProgressBarMaxWidth: 0,
  formsWithStepsProgressBarLine:new Array(),
  formsWithStepsProgressPoint1stMarked: 13,
  formsWithStepsProgressPointWidthFixer: 5,
  formsWithStepsBlock:false,
  
    __init__ : function() {
  },

  domready : function() {
      this.addShadows();
      this.fixElementsPosition();
      this.initNivoslider();
      this.initForms();
      this.initCufonFonts();
      this.initSearch();
      this.addSTUrl();
      this.initExpandableNewsList();
      this.initExpandableList();
      this.initCheckActiveMenu('ul#topmenu');
      this.initCheckActiveMenu('ul#bottommenu');
      this.initClientsAnimation();
      this.insertGoogleMap();
  },
  
  onCufonReady : function() {
      this.initBoxy();
      this.ieFix();
  },

  isDomReady : function(){
    if (jQuery.browser.safari){ 
        if (document.readyState != "complete") {
            setTimeout( function(){ main.isDomReady(); }, 1000 );
            return;
        } else {
            main.domready();
        }
    } else {
        main.domready();
    }

  },

  fixElementsPosition: function(){
      if('#newsBoardBlock .stWidget'){
          var imgHeight = $('#newsBoardBlock li.first a.img').height();
          var spanHeight = $('#newsBoardBlock li.first span.txt').height();
          if(imgHeight > spanHeight) $('#newsBoardBlock .stWidget').css('margin-top', imgHeight-spanHeight + 'px');
          else $('#newsBoardBlock .stWidget').css('margin-top', '4px');
      }
      var footerHeight = $('#footer .txt').height() + $('#footer .links').height() + parseInt($('#footer .links').css('margin-bottom'));
      $('#footer, #push').height(footerHeight);
      $('#wrapper').css('margin-bottom', -footerHeight);
  },
  
  initCufonFonts: function(){
      //Cufon.replace('.LucidaGrande,h2', { fontFamily: 'LucidaGrande', hover: false });
      $('html').addClass('cufon-ready');
      this.isCufonReady();
  },
  
  isCufonReady : function(){
      if (!$('html').hasClass('cufon-ready')) {
          setTimeout( function(){ main.isCufonReady(); }, 500 );
          return;
      } else {
          main.onCufonReady();
      }
  },
  
  addShadows: function(){
      ($('.dropShadow')).dropshadow();
  },
  
  initNivoslider: function(){
      if($('#sliderBlock')) {
          $('#sliderBlock').nivoSlider({
              directionNav:false,
              controlNav:true,
              pauseOnHover:true,
              pauseTime:7000,
              animSpeed:500
          });
      }
  },
  
  saveSettings: function(form){
      var defaultSection = $('#settings_startupSection').val();
      $.cookie('smarttech_default_section', defaultSection, { expires: 365 });
      var defaultLang = $('#settings_startupLanguage').val();
      $.cookie('smarttech_default_lang', defaultLang, { expires: 365 });
      var keepLogged = $('#settings_keepLogged').val();
      $.cookie('smarttech_keep_logged', keepLogged, { expires: 365 });
      
      main.closeBoxy();
  },
  
  add2Newsletter: function(form){
      $(form).find('button').hide();
      $(form).find('.loader').show();

      jQuery.ajax({  
          type: "POST",
          url: $(form).attr('action'),  
          data:  $(form).serialize(),
          error: function() {
              console.log("Failed to submit - ");
          },
          success: function(r) {
              $(form).find('.loader').hide();
              $(form).find('button').show();
              var result = $.parseJSON(r);

              if(result.status=='ok'){
                  $('#subscribeNewsletterBox .div_form').hide();
                  $('#subscribeNewsletterBox .div_info').show();
                  
                  $('#subscribeNewsletterBoxClose').bind('click', function(){ 
                      main.closeBoxy();
                      $('#newsletterForm').get(0).reset();
                      $('#subscribeNewsletterBox .div_form').show();
                      $('#subscribeNewsletterBox .div_info').hide();
                  });
              } else {
                  $('#newsletterForm input').addClass('error');
//                $('#form_newsletter_result').html(result.msg);
              }
          } 
    });
  },
  
  formShowErrors: function(errors, input){
      if($.makeArray(errors).length){
          $.each(errors, function(index, value){
        	  if(!input || index==$(input).attr('name')){
            	  var errorObj = $(input).parent().find('.error_msg');
            	  if(!errorObj[0]){
            		  var errorObj = $('<span class="error_msg" />');
            		  errorObj.insertBefore($(input));
            	  } else {
            		  // nothing
            	  }

            	  if(value!=null){
                	  errorObj.html(value);
                	  errorObj.fadeIn(1500);
                	  $(input).parent('label').addClass('error');
                  } else {
                	  errorObj.fadeOut();
                  }
              }
          });
          return true;
      } else {
          return false;
      }
  },
  
  formSubmit: function(form, callback, nourlchange){
      var btnElement = $(form).find('button');
      
      btnElement.hide();
      $(form).find('.loader').show();

      var posturl = $(form).attr('action');
      if(!nourlchange) posturl+=btnElement.attr('value');
      var formData = $(form).serialize();
      
      var formBtn = $(form).find('button[name=submitBtn]');
      var formBtnName = formBtn.attr('name');
      var formBtnValue = formBtn.attr('Value');
      
      if(formBtnName!='' && formBtnValue!='') {
    	  formData = formData + '&' + formBtnName + '=' + formBtnValue;
      }

      jQuery.ajax({  
          type: "POST",
          url: posturl,
          data:  formData,
          error: function() {
              console.log("Failed to submit - ");
          },
          success: function(r) {
              var result = $.parseJSON(r);
              
              if(result.status=='error'){
            	  $(form).find('input,textarea').each(function(){
            		  main.formShowErrors(result.errors, $(this));
            	  });
                  //main.formShowErrors(result.errors);
              } else {
                  main.closeBoxy();
                  if(!callback){
                      $('#messageBox .messageBoxMsg').html(result.msg);
                      new Boxy($('#messageBox').clone(), {modal:true, draggable: true, closeText:'', closeable:true, show:true, title:'Message',unloadOnHide:true });
                  } else {
                      callback();
                  }
              }
              $(form).find('.loader').hide();
              $(form).find('button').show();
          }
    });
  },

  validateForm: function(input, nourlchange){
      form = $(input).closest('form');
      var posturl = form.attr('action');
      if(!nourlchange) posturl+='/validate';

      jQuery.ajax({ 
          type: "POST",
          url: posturl,
          data:  form.serialize(),
          error: function() {
              console.log("Failed to submit - ");
          },
          success: function(r) {
              var result = $.parseJSON(r);
              main.formShowErrors(result.errors, input);
          }
     }); 
  },
  
  closeBoxy: function(){
      $('#boxyCloseBtn').trigger('click');
  },
  
  initForms: function(){
	  /*
      $('form button[type=submit]').each(function(){
          $(this).bind('click', function(){ 
              form = $(this).closest('form');
              $(form).submit();
              return false;
          });
      });
*/
      $('.watermarked').each(function() {
          $(this).watermark($(this).attr('title'), 'watermark');
      });
      
      $('#settingsForm').live('submit', function(){ main.saveSettings(this); return false; });
      $('#newsletterForm').live('submit', function(){ main.add2Newsletter(this); return false; });
      
      $('#registrationForm').live('submit', function(){ main.formSubmit(this); return false; });
      $('#registrationForm input').live('blur', function(){ main.validateForm(this); return false; });
      $('#registrationForm input').live('focus', function(){ $(this).parent().find('.error_msg').fadeOut(); return false; });
      $('#ftocFormMns').live('submit', function(){ main.formSubmit(this, false, true); return false; });
      $('#ftocFormMns input').live('blur', function(){ main.validateForm(this, true); return false; });
      $('#ftocFormMns input').live('focus', function(){ $(this).parent().find('.error_msg').fadeOut(); return false; });
      $('#ftocFormMpc').live('submit', function(){ main.formSubmit(this, false, true); return false; });
      $('#ftocFormMpc input').live('blur', function(){ main.validateForm(this, true); return false; });
      $('#ftocFormMpc input').live('focus', function(){ $(this).parent().find('.error_msg').fadeOut(); return false; });
      $('#ftocFormOdb').live('submit', function(){ main.formSubmit(this, false, true); return false; });
      $('#ftocFormOdb input').live('blur', function(){ main.validateForm(this, true); return false; });
      $('#ftocFormOdb input').live('focus', function(){ $(this).parent().find('.error_msg').fadeOut(); return false; });
      $('#ftocFormV').live('submit', function(){ main.formSubmit(this, false, true); return false; });
      $('#ftocFormV input').live('blur', function(){ main.validateForm(this, true); return false; });
      $('#ftocFormV input').live('focus', function(){ $(this).parent().find('.error_msg').fadeOut(); return false; });
      
      $('#freenetworkauditForm').live('submit', function(){ main.formSubmit(this); return false; });
      $('#freenetworkauditForm input').live('blur', function(){ main.validateForm(this); return false; });
      $('#freenetworkauditForm input').live('focus', function(){ $(this).parent().find('.error_msg').fadeOut(); return false; });
  
      $('#loginForm').live('submit', function(){ main.formSubmit(this, function(){ location.reload(); }); return false; });
      
      if ($('form.formWithSteps').length) main.initFormWithSteps();
  },
  
  formWithStepsMoveText:function(formObj, listObj, direction, pageWidth, currentPage, pagesCount){
	  
	  if(direction=='1'){ // next
	  } else { // prev
	  }

	  main.formsWithStepsBlock=true;
	  $(listObj).animate({
		  'margin-left': -(pageWidth*(currentPage-1))
	  	}, 1000, function(){ main.formWithStepUpdateProgressBar(formObj, currentPage, pagesCount); main.formsWithStepsBlock=false; });
  },

  formWithStepUpdateProgressBar:function(formObj, currentPage, pagesCount){
	  if(currentPage==1 || currentPage==pagesCount){
		  if(currentPage==1){
			  var progressWidth = main.formsWithStepsProgressPoint1stMarked;
		  } else {
			  var progressWidth = main.formsWithStepsProgressBarMaxWidth; 
		  }
	  } else {
		  var distance = main.formsWithStepsProgressBarMaxWidth/2*(pagesCount-2);
		  var progressWidth = (currentPage-1)*distance+main.formsWithStepsProgressPointWidthFixer;
	  }

	  $(formObj).prev().find('.formStepsProgressBox .red').css('width', progressWidth);
  },
  
  formWithStepsChangePage:function(btnObj, direction){
	  if(main.formsWithStepsBlock==false){
		  var formObj = $(btnObj).closest('form.formWithSteps');
		  var formId = formObj.attr('id');
		  var ulId = $(btnObj).parent('.btnContainer').prev('.formStepsContainter').find('ul.steps');
		  var pagesCount = $(formObj).find('ul.steps li').length;
		  var pageWidth = main.formsWithStepsPageWidth[formId];
		  var currentMargin = parseInt(ulId.css('margin-left'));  
		  var currentPage = -(currentMargin/pageWidth)+1;
	
		  if (direction=='1' && currentPage<pagesCount){ // next
				  	 currentPage++;			  
		  }else { if(direction=='0' && currentPage>1){ // prev
				     currentPage--;			  
			  	 }
		  }
		  main.formWithStepsMoveText(formObj, ulId, direction, pageWidth, currentPage, pagesCount);
	  }
  },
  
  hideFormErrors:function(obj){
	  var objName = $(obj).attr('name');
      form = $(obj).closest('form');
	  $(form).find('[name='+objName+']').each(function(){
		  $(this).parent().find('.error_msg').fadeOut();
	  });
	  
	  return false;
  },
  
  initFormWithSteps:function(){
	  $('form.formWithSteps').each(function(){
		  var formId = $(this).attr('id');
		  var formStepsProgressBox = $(this).prev().find('.formStepsProgressBox');
		  main.formWithStepUpdateProgressBar($(this), 1, $(this).find('ul.steps li').length);
		  
		  if(main.formsWithStepsProgressBarMaxWidth==0) main.formsWithStepsProgressBarMaxWidth = parseInt($(formStepsProgressBox).find('.white').css('width'));
		  main.formsWithStepsPageWidth[formId] = parseInt($(this).find('.formStepsContainter').css('width'));
		  
		  $(this).find('.formStepsBtnPage').each(function(){
			  $(this).bind('click', function(){ main.formWithStepsChangePage(this, $(this).attr('value')); });
		  });
		  
	      $(this).bind('submit', function(){ main.formSubmit(this, false, true); return false; });
	      $(this).find('input').live('blur', function(){ main.validateForm(this, true); return false; });
	      $(this).find('input').live('focus', function(){ return main.hideFormErrors(this); });
	  });

  },
 
  initBoxy: function(){
      $('.boxyBtn').each(function() {
          $(this).boxy({modal:true, draggable: true, closeable: true, closeText:'', clone:false });
        });
  },

  initSearch: function(){
    this.suggestionsSearch = new SuggestionsSearch();
    $('#searchform input').keyup(function(){ main.suggestionsSearch.lookup($(this).parent('form').attr('action'), this.value); });
  },
  
  addSTUrl: function(){
      if($('#stWidget')){
          var stUrl = $('#stWidget').attr('title');
          $('#stWidget .st_sharethis').attr('st_url', stUrl);
      }
  },
  
  expandNewsElement:function(element){
      element.find('.short').fadeOut(200, function(){
          element.find('.fRight .long').fadeIn(1000, function(){
              element.addClass('active');
          });
      });
  },
  
  toggleExpandableNews: function(currentElement){
      var activeNews = $('#newsBoardBigList li.active');
      activeNews.find('.long').fadeOut(200, function(){
          activeNews.find('.short').fadeIn(500, function(){
              activeNews.removeClass('active');
              main.expandNewsElement(currentElement);
          });
      });
  },
  
  initExpandableNewsList: function(){
      if($('#newsBoardBigList')){
          $('#newsBoardBigList li').each(function(){
              $(this).bind('click', function(){ 
                  if(!$(this).hasClass('active')){
                      main.toggleExpandableNews($(this));
                  }
                  return false;
              });
          });
          
          $('#newsBoardBigList li .long a').each(function(){
              $(this).bind('click', function(e){
                  e.stopPropagation();
              });
          });

          main.expandNewsElement($('#newsBoardBigList li:first-child'));
      };
      main.expandElement($('#newsBoardBigList li:first-child'));
  },
  
  expandElement:function(element){
      element.children('.long').fadeIn(1000, function(){
              element.addClass('active');
          });
  },

  toggleExpandableList: function(currentElement){
      var activeNews = $('.expandableList li.active');

      if(activeNews.hasClass('active')){
          activeNews.children('.long').fadeOut(200, function(){
                  activeNews.removeClass('active');
                  main.expandElement(currentElement);
              });
      }else{
          main.expandElement(currentElement);
      }
  },  

  initExpandableList: function(){
      if($('.expandableList')){
          $('.expandableList li').each(function(){
              $(this).bind('click', function(){ 
                  if(!$(this).hasClass('active')){
                      main.toggleExpandableList($(this));
                  }
                  return false;
              });
          });
          
          $('.expandableList li a').each(function(){
              
              $(this).bind('click', function(e){ 
                  e.stopPropagation();
              });
          });
          
//        main.expandElement($('.expandableList li:first-child'));
      };
  },
  
  initClientsAnimation: function() {
      if ($('#clientsBox ul')){
          var activeElement = $('#clientsBox ul li.active');
          activeElement.removeClass('active');
          nextActiveElement = activeElement.next();
          if(nextActiveElement.html() == null)
              nextActiveElement = $('#clientsBox ul li:first-child');
          nextActiveElement.addClass('active');
          
          activeElement.fadeOut(1000, function(activeElement){
              $('#clientsBox ul li.active').fadeIn(1000, function(){ 
                  setTimeout('main.initClientsAnimation()', 3000); 
              });
          });
      }
  },
  
  initCheckActiveMenu: function(pattern) {
        
        var path = document.location.pathname.substr(1);
        if(path.charAt(path.length-1) == '/') path = path.substr(0, path.length-1);
        else if(path == '') path = '/';
        path = path.replace(/\/\d+\/?$/, '').replace(/\/[0-9a-z-]+\.html\/?$/, '');
        
        var links = $(pattern+' a[href='+path+']');

        while(links.length == 0 && path != '') {
            path = path.split('/');
            path.pop();
            path = path.join('/');
            links = $(pattern+' a[href='+path+']');
        }
        
        if(links.length == 1) {
            links.parent('li').addClass('active');
        }
    }, //initCheckActiveMenu
    
    putMap:function(container){
        var reg = new RegExp('\\[(.+)\\]');
        var pos = reg.exec($(container).html());
        pos = pos[1].split(';');
        var myLatlng = new google.maps.LatLng(pos[0], pos[1]);
        var myOptions = {
          zoom: 12,
          center: myLatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          navigationControlOptions: {
              style: google.maps.NavigationControlStyle.ZOOM_PAN
          }
      };

      map = new google.maps.Map($(container)[0], myOptions);
      var marker = new google.maps.Marker({
          position: myLatlng, 
          map: map
      });
    },
    
    insertGoogleMap: function() {
          if($('#gmap').length){
        	  main.putMap($('#gmap'));
          }
          
          if($('.gmap').length){
        	  $('.gmap').each(function(){
        		  main.putMap($(this));
        	  });
          }
    }, // insertGoogleMap

    showMail: function(user, domain, contry, attr) {
        var start = "<a href=\"mailto:" + user + "@" + domain + "." + contry + "\"" + attr + ">";
        var end = "</a>";
        document.write(start + user + "@" + domain + "." + contry + end);
        return false;
    }, // showMail

    ieFixZIndex:function(){
        $(function() {
               var zIndexNumber = 1000;
               $("div").each(function() {
                       $(this).css('zIndex', zIndexNumber);
                       zIndexNumber -= 10;
               });
        });
    },

    ie7MenuFix:function(){
        $('#topMenu li ul').each(function(){
            var maxWidth = 0;
            $(this).find('li a span cufon').each(function(){
                var curWidth = $(this).attr('alt').length*10;
                if(curWidth>maxWidth) maxWidth=curWidth;
            });
            $(this).find('li').each(function(){
                $(this).width(maxWidth);
                $(this).find('a').width(maxWidth);
            });
            $(this).height($(this).height()-3);
        });
    },
    
    ieFixCategoryBtns:function(){
        $('ul.subsiteList li a button .leftC .rightC .txt cufon').each(function(){
            var cufonWidth = $(this).width();
            
            $(this).parent('.txt').width(cufonWidth);
            var spanRightCObj = $(this).closest('.rightC');
            var spanLeftCObj = $(this).closest('.leftC');
            spanRightCObj.width($(this).width());
            $(this).closest('.btn').width( cufonWidth+
                    parseInt(spanLeftCObj.css('padding-left'))+
                    parseInt(spanRightCObj.css('padding-right')) );
        });

        $('ul.subsiteList li a .img').each(function(){
            var pngPath =  $(this).css('background-image');
            $(this).css('background-image', 'none');
            $(this).css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=\'true\',src=\'/'+pngPath+'\', sizingMethod=\'crop\')');
        });
    },

    ieFix:function(){
        if($.browser.msie){
            this.ieFixCategoryBtns();

            if(jQuery.browser.version == 8){
            } else if(jQuery.browser.version == 7){
                this.ie7MenuFix();
            }
        }
    }
});

main = new Main();

$(document).ready(function(){
    main.isDomReady();
});

