// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var switchingTabInProgress = false;
var newTabNum = 1;
function switchTab(boxID, tabNum){
	if (switchingTabInProgress)
		return;
  
  var tabs = $$("#"+boxID+" .tabs .tab");
  tabs.each(function(c){
    c.removeClassName("active");
    c.removeClassName("previous-active");
    c.removeClassName("next-active");
  });
  tabs[tabNum - 1].addClassName("active");
  if (tabNum > 1) tabs[tabNum - 2].addClassName("next-active");
  if (tabNum < tabs.length) tabs[tabNum].addClassName("previous-active");

  var contents = $$("#"+boxID+" .contents .content");

  contents.each(function(c){
	  	  
	  
		if (c.hasClassName("active") && c != contents[tabNum - 1]) {
			var content_height = (c.getHeight());		
			
			var container = $$('.contents')[0];
			container.setStyle ({height: content_height+'px'}); //nejde mi ziskat vysku => nastavena vetsi nez predpokladana
			
			switchingTabInProgress = true;

			newTabNum = tabNum - 1;
			c.fade({duration: 1, afterFinish: function(effect) {
					effect.element.removeClassName("active");
				}, queue: {scope: 'menus', position: 'end'}
			});
			contents[newTabNum].appear({duration: 1, afterFinish: function(effect) {
					switchingTabInProgress = false;
				}, afterSetup: function(effect) {
					effect.element.addClassName("active");
				}, queue: {scope: 'menus', position: 'end'}
			});
		  setTimeout(function(){container.setStyle ({height: 'auto'})}, 1750); //zmena vysky po animaci zpet
		}
	});
}

function changeFilter(path, className) {
  $$(path+' .content > div').each(function(c){
    if (c.hasClassName(className)) {
      c.removeClassName('hidden');
    } else {
      c.addClassName('hidden');
    }
  });

  $$(path+" .bottom-tab-options li").each(function(c){
    if (c.hasClassName(className)) {
      c.addClassName('active');
    } else {
      c.removeClassName('active');
    }
  });
}

function flashPlayer(){
  //delky jednotlivych flashu
  var moviesLenght = new Array(
    11 * 1000, // 1
    12 * 1000, // 2
    16 * 1000, // ...
    16 * 1000,
    41 * 1000
  );

  // poradi videi
  // - pokud se zmeni 1. video, musi se jeste prepsat ve views!
  var moviesOrder = new Array(1,4,2,5,3);

  // vymeni flash
  var changeFlash = function(movieNum){
    // smaze stary flash
    if ($('flash-object')) {
      swfobject.removeSWF('flash-object');
    }

    // vytvori div pro novy
    var flash_div = new Element('div', {'id': 'flash-object'});
    $("movie-wrapper").appendChild(flash_div);

    // vlozi novy flash
    var att = {
      data: "flash/"+movieNum+".swf",
      width: "996",
      height:"226"
    };
    var par = {
      wmode: "transparent"
    };
    var id = "flash-object";
    swfobject.createSWF(att, par, id);
  }

  // cyklicky meni videa
  var i = 0;
  var alterFn = function(){
    i = i + 1;
    if (i > moviesLenght.length - 1) i = 0;
    var currentMovie = moviesOrder[i];
    changeFlash(currentMovie);

    setTimeout(alterFn, moviesLenght[currentMovie - 1])
  }
  changeFlash(1);
  setTimeout(alterFn, moviesLenght[moviesOrder[0] - 1]); // cekam kvuli prvnimu videu


}



// shadowbox extensions
var shadowboxConfig = (function(){
  (function changeSkin() {
    var S = Shadowbox, U = S.util;

    function toggleNav(id, on){
        var el = U.get('sb-nav-' + id);
        if(el) el.style.display = on ? '' : 'none';
    }

    function updateNav(obj) {
      var len = S.gallery.length;
      var n,p;
      if (len > 1){
          if (S.options.continuous)
              n = p = true; // show both
          else{
              n = (len - 1) > S.current; // not last in gallery, show next
              p = S.current > 0; // not first in gallery, show previous
          }
      }

      toggleNav('content-previous', p);
      toggleNav('content-next', n);
    }

    S.options.onChange = updateNav;
    S.options.onOpen = updateNav;

    var prevHTML = '<a id="sb-nav-content-previous" href="#predchozi" onClick="this.blur();Shadowbox.previous();return false;"></a>';
    var nextHTML = '<a id="sb-nav-content-next" href="#dalsi" onClick="this.blur();Shadowbox.next();return false;"></a>';

    S.skin.markup = S.skin.markup.sub(/(<div[^>]+id="sb-body"[^>]*>)/, "#{1}"+prevHTML+nextHTML);

    var closeHTML = '<a id="sb-nav-content-close" href="#zavri" onClick="Shadowbox.close();return false;"></a>';
    S.skin.markup = S.skin.markup.sub(/(<div[^>]+id="sb-title"[^>]*>)/, "#{1}"+closeHTML);
  })();

  return {
    players:    ['img', 'swf', 'flv', 'iframe', 'html'],
    overlayColor: '#000',
    overlayOpacity: 0.8,
    flashParams: {
      bgcolor: '#fff'
    },
    initialHeight: 160,
    displayNav: false,
    viewportPadding: 0
  }
});


// v tabulce o SCUDeCRM vytvori v lightboxu leve menu
function scudecrmCreateMenus(){
  var table = $$('.crm-table').first();
  if (typeof table != 'object') return false;

  // zapise si hlavni nadpisy
  var nadpisy = new Array();
  table.select('.box h3').each(function(i){
    nadpisy.push(i.innerHTML);
  });

  // projde vsechny boxy a zapise si nadpisy a id
  var boxy = new Array();
  for (i=0; i<nadpisy.length; i++) {
    boxy[i] = new Array();
  }
  $$('.crm-table-light').each(function(tbl,row){
    tbl.select('.box-blank','.box').each(function(box,col){
      var nadpis = box.select('h3').first();
      var shadowbox_detail = box.select('.shadowbox-detail').first();

      if (shadowbox_detail) {
        boxy[col][row] = new Array(
          nadpis.innerHTML,
          shadowbox_detail.getAttribute('id')
        );
      }
    });
  });

  // prida do DOMu menu
  $$('.crm-table-light').each(function(tbl, row){
    tbl.select('.box-blank','.box').each(function(box,col){
      var shadowbox_detail = box.select('.shadowbox-detail').first();

      if (shadowbox_detail) {
        var menu_wrapper = new Element('div');
        menu_wrapper.className = "shadowbox-menu";
        var title = new Element('h3').update(nadpisy[col]);

        var menu = new Element('ul');
        boxy[col].each(function(item){
          var li = new Element('li');
          var link = new Element('a',{
            href: '#'+item[1],
            title: item[0],
            // musim zapsat jako text kvuli shadowboxu
            onclick: "Shadowbox.open({"+
                        "content: $('"+item[1]+"').innerHTML,"+
                        "player: 'html',"+
                        "title: '"+item[0]+"',"+
                        "width: 700,"+
                        "height: 450,"+
                        "wrapperclass: '" + item[1] + "'" + //trida pro div id="sb-wrapper"
                      "});"+
                      "return false;"
            //'class': shadowbox_detail.getAttribute('id') == item[1] ? "active" : ''  //bug v IE8
          }).update(item[0]);
          link.className = shadowbox_detail.getAttribute('id') == item[1] ? "active" : ''
          li.appendChild(link);

          menu.appendChild(li);
        });

        menu_wrapper.appendChild(title);
        menu_wrapper.appendChild(menu);
        shadowbox_detail.appendChild(menu_wrapper);
      }
    });
  });

  // zvetsi sirku Shadowboxu o sirku menu
  $$('.crm-table-light [rel="shadowbox"]').each(function(link){
    var href=link.getAttribute('href');
    href = href.substring(1);
    link.setAttribute('rel', "shadowbox;width=700;height=450;wrapperclass="+href);
  });
}

// policka s textem, ktery se pri focusu skryje
function switch_value(el, default_value, action) {
	if (action == 'focus' && default_value == el.value) {
		el.value = '';
	} else if (action == 'blur' && el.value == '') {
		el.value = default_value;
	}
}

// zrusi klasicke odesilani formulare a misto toho pouzije Ajax
function ajaxForm(form, success, failure, beforeSubmit) {
  form.observe('submit', function(e){
    e.stop();
    if (typeof beforeSubmit == "function" && beforeSubmit.apply(this) === false)  return false;
    
    this.request({
      onSuccess: function(response) {
        success.apply(this, [response.responseText.evalJSON(), response]);
      },
      onFailure: failure.bind(this)
    });
  });
}

// zda text odpovida emailu
function validateEmail(email) {
   var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return regex.test(email);
}

// send to friend - ajaxForm s nastavenymi callbacky
function stfAjaxForm(id, n) {
  var failureMsg = 'Vyskytla se chyba, zkuste prosím známého pozvat znovu.';
  var submitMsg = 'Odesílám...';
  var successMsg = 'Doporučení odesláno.'
  var form = $(id);
  var notifications = $(n);

  ajaxForm(form,
    // success
    function(json, response){
      if (typeof json == "object" && json.success) {
        form.reset();
        notifications.update(json.message || successMsg);
      } else {
        notifications.update(json.message || failureMsg);
      }
    },

    // failure
    function(response){
      notifications.update(failureMsg);
    },

    // beforeSubmit
    function(){
      // validace
      var name_input = form.getInputs('text','stf_name').first();
      var name = name_input.getValue();
      var email_input = form.getInputs('text','stf_mail').first();
      var email = email_input.getValue();
      var antispam_value =  $('antispam').value;
      if (name == name_input.defaultValue || name.length < 4) {
        notifications.update('Vyplňte Vaše jméno.');
        name_input.focus();
        return false;
      }
      if (email == email_input.defaultValue || !validateEmail(email)) {
        notifications.update('Vyplňte správný e-mail.');
        email_input.focus();
        return false;
      }
      
      if (antispam_value != 'anti_spam_control') {
        notifications.update('Anti-spamová kontrola selhala.');
        return false;
      }
      
      // zobraz loading
      notifications.update(submitMsg);
    }
  );
}

function cfAjaxForm(id, n) {
  var failureMsg = 'Vyskytla se chyba, zkuste prosím Vaši zprávu poslat znovu.';
  var submitMsg = 'Odesílám...';
  var successMsg = 'Zpráva odeslána.'
  var form = $(id);
  var notifications = $(n);

  ajaxForm(form,
    // success
    function(json, response){
      if (typeof json == "object" && json.success) {
        form.reset();
        notifications.update(json.message || successMsg);
      } else {
        notifications.update(json.message || failureMsg);
      }
    },

    // failure
    function(response){
      notifications.update(failureMsg);
    },

    // beforeSubmit
    function(){
      // validace
      var name_input = form.getInputs('text','cf_name').first();
      var email_input = form.getInputs('text','cf_email').first();
      var message_input = form.cf_message;
      var name = $F('cf_name');
      var email  = $F('cf_email');
      var message  = $F('cf_message');
      
      if (name.length < 4) {
        notifications.update('Vyplňte Vaše jméno.');
        name_input.focus();
        return false;
      }
      if (!validateEmail(email)) {
        notifications.update('Vyplňte správný e-mail.');
        email_input.focus();
        return false;
      }
      
      if (message == ''){
        notifications.update('Vyplňte text zprávy.');
        message_input.focus();
        return false;
      }
      
      // zobraz loading
      notifications.update(submitMsg);
    }
  );
}

function launch_carousel() {
	jQuery(document).ready(function() {
		jQuery('#jcarousel').jcarousel({ scroll: 1, visible: 1,	auto: 3, wrap: 'last', initCallback: jcarousel_initCallback	});
	});
}

function jcarousel_initCallback(carousel)	{
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});

	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});

	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});
};
