/* various small JS functions for the site */

var toppage_quotes = [
  "Because really good work beats great claims every time.",
  "We thought we’d spare you the superlatives and just make it damn good.",
  "<strong>good</strong> [good] adjective:<br>useful, profitable, excellent and right. Enough said.",
  "Because really good work beats great claims."
];
var toppage_current_quote_idx;
var animation_in_progress;

//-------------------------------------------------------------

function not_implemented() {
  var msgs = [
    "functionality coming soon!",
    "coming soo...ner or later!",
    "working on it!",
    "can't have it all :)",
    "prioritized development in progress. stay tuned!",
    "ouch! didn't expect you click here! please unclick.",
    "nope. it doesn't work. but it will soon :)"
  ];
  var idx = Math.ceil(Math.random()*msgs.length)
  alert(msgs[idx-1]);
}

//=============================================================

function toppage_init() {
  document.observe("dom:loaded", toppage_wire);
}

var shared_timer;
var toppage_auto_switch_timer;
var pulseEffect;

function toppage_wire() {
  var link = $$("#why_good a").first();
  var goodblock = $("good_block");
  if (!isTouchDevice()) {
    link.observe("mouseover", toppage_great_switch);
    link.observe("mouseout", toppage_great_out_fromgood);
    link.observe("click", toppage_great_click);
    
    goodblock.observe("mouseover", toppage_great_switch);
    goodblock.observe("mouseout", toppage_great_out_fromgood);
    goodblock.observe("click", toppage_great_click);
  } else {
    //touch-capable devices wiring
    link.observe("click", toppage_great_touch);
    goodblock.observe("click", toppage_great_touch);
  }

  toppage_auto_switch_timer = null;
  toppage_current_quote_idx = 1;
  animation_in_progress = false;
  pulseEffect = null;
  toppage_set_quote();
}

function toppage_great_switch(evt) {
	//switching on rollover for non-touch-capable devices
  Event.stop(evt);

  if (animation_in_progress) return false;
  animation_in_progress = true;

  var link = $$("#why_good a").first();
  //link.removeClassName("unhilited");

  toppage_great_over_fromgood();
  toppage_next_quote.delay(0.35);
  //toppage_great_out_fromgood.delay(2);

  if (toppage_auto_switch_timer!=null) {
	clearInterval(toppage_auto_switch_timer);
  }
  toppage_auto_switch_timer = setInterval(toppage_next_quote, 4000);

  setTimeout(function() {
    animation_in_progress = false;
    var link = $$("#why_good a").first();
    //link.removeClassName("hilited");
    //link.addClassName("unhilited");
  }, 2000);
}

function toppage_great_touch(evt) {
  Event.stop(evt);

  if (animation_in_progress) return false;
  animation_in_progress = true;

  var link = $$("#why_good a").first();
  link.removeClassName("unhilited");

  toppage_great_over_fromgood();
  toppage_next_quote.delay(0.6);
  toppage_great_out_fromgood.delay(2);

  setTimeout(function() {
    animation_in_progress = false;
    var link = $$("#why_good a").first();
    link.removeClassName("hilited");
    link.addClassName("unhilited");
  }, 2000);
}

function toppage_great_over_fromgood() {
  toppage_great_over();
  if (shared_timer!=undefined) {
    clearTimeout(shared_timer);
    shared_timer = undefined;
  }
  shared_timer = setTimeout(function () {
    var link = $$("#why_good a").first();
    link.addClassName("hilited");
  }, 350);
}
function toppage_great_out_fromgood() {
  if (toppage_auto_switch_timer!=null) {
	clearInterval(toppage_auto_switch_timer);
  }
  toppage_auto_switch_timer = null;
	
  toppage_great_out();
  var link = $$("#why_good a").first();
  link.removeClassName("hilited");
  if (shared_timer!=undefined) {
    clearTimeout(shared_timer);
  }
  shared_timer = undefined;
}
function toppage_great_over() {
  $('dots').setStyle({display:"block", width:"0px"});
  $('dots').setOpacity(0);
  new Effect.Morph($('dots'), {style:'width:100px; opacity:1', duration: 0.3});
}
function toppage_great_out() {
  $("dots").hide();
}
function toppage_great_click(evt) {
  Event.stop(evt);
  if (toppage_auto_switch_timer!=null) {
	clearInterval(toppage_auto_switch_timer);
  }
  toppage_auto_switch_timer = null;
  if (!animation_in_progress) {
    toppage_next_quote();
  }
}

function toppage_set_quote() {
  $("phrase").update(toppage_quotes[toppage_current_quote_idx-1]);
}
function toppage_next_quote() {
  animation_in_progress = true;

  if (Prototype.Browser.IE) {
    //no alpha animation for text in IE as it comes out jagged
    new Effect.Morph("phrase", {style:'top:-110px', duration: 0.3, afterFinish: toppage_animate_new_in});
  } else {
    new Effect.Morph("phrase", {style:'top:-110px; opacity: 0', duration: 0.3, afterFinish: toppage_animate_new_in});
  }

}
function toppage_animate_new_in() {
  toppage_current_quote_idx += 1;
  if (toppage_current_quote_idx>toppage_quotes.length) toppage_current_quote_idx=1;
  toppage_set_quote();
  new Effect.Morph("phrase", {style:'top:0px; opacity: 1', duration: 0.6, afterFinish: toppage_animate_cleanup});
}
function toppage_animate_cleanup() {
  animation_in_progress = false;
}
//-------------------------------------------------------------- SHARED STUFF

var tmp; //for passing various stuff
function init_submenu(submenu_idx) {
  tmp = submenu_idx;
  //document.observe("dom:loaded", wire_submenu);
  Event.observe(window, "load", wire_submenu);
}
function position_submenu(idx) {
  var elt1 = $$("#header ul.main li")[idx-1];
  var elt2 = $$("#header .subhead")[0];

  var subhead_width = elt2.getWidth();

  var moveby = elt1.cumulativeOffset().left-elt2.cumulativeOffset().left;
  var newleft = parseInt(elt2.getStyle("left"))+moveby;

  if ( (newleft+subhead_width)>$("header").getWidth() ) {
    elt2.setStyle({width: subhead_width+"px"});
    newleft = $("header").getWidth()-subhead_width +5; //5 for right padding
  }

  newleft += "px";
  elt2.setStyle({left:newleft, display:'none'});
  elt2.appear({duration:0.5});
}
function wire_submenu() {
  var submenu = $$("#header .subhead")[0];
  if (submenu==undefined) return;

  //wiring scroll events
  $$("#header .subhead a").each(function(elt) {
    elt.observe("click", submenu_doscroll);
  });

  //absolutizing anchors
  submenu_absolutize_anchors.delay(0.3);

  //positioning element under correct toplevel elt
  var idx = tmp;
  if (idx==undefined) idx=1;
  position_submenu.delay(0.3, idx);

}

function submenu_absolutize_anchors() {
  $$("a[name]").each(function(elt){
    elt.absolutize();
    var newtop = parseInt(elt.getStyle("top"))-$("header").getHeight() -1;
    if ($$("#content .hero").length>0) {
      //need to move it down 2 px for border-less pages with hero img
      newtop -= 3;
    }
    newtop += "px";
    elt.setStyle({top: newtop});
  });

  //hiliting submenu item
  if (document.location.hash.length>1) {
    //have a hashtag
    submenu_scrollto(document.location.hash.replace("#", ""));
  } else {
    //no hashtag, selecting first elt in submenu
    $$("#header .subhead a")[0].addClassName("current");
  }
}

function submenu_doscroll(evt) {
  Event.stop(evt);

  var elt = evt.element();
  var hash = elt.href.split("#")[1];
  submenu_scrollto(hash);
}
function submenu_scrollto(hashtag) {
  var anchor = $$("a[name='"+hashtag+"']")[0];
  if (anchor==undefined) console.log("scroll position not found:" + hashtag);

  //removing 'current' classname from all
  $$("#header .subhead a").each(function(elt) {
    elt.removeClassName("current");
  });

  var elt = $$("#header .subhead a[href='#"+hashtag+"']");
  if (elt.length==0) {
    document.location.hash = '';
    return false;
  }
  elt[0].addClassName("current");

  new Effect.ScrollTo(anchor, {
    duration: 0.5,
    afterFinish: function() {
      document.location.hash = hashtag;
    }.bind(this)
  });
}

//====================================================

var about_active_panel;
var about_next_panel;
var about_page_animation_inprogress;

function about_init() {
  document.observe("dom:loaded", about_wire);
  about_active_panel = null;
  about_next_panel = null;
  about_page_animation_inprogress = false;
}
function about_wire() {
  $("team_slider").observe("click", about_click_dispatch);
  $$("#controls .prev")[0].observe("click", about_prev_page);
  $$("#controls .next")[0].observe("click", about_next_page);

  //duplicating first column to the tail for looping
  $("team_slider").appendChild($$("#team_slider .column")[0].clone(true));
  $("team_slider").appendChild($$("#team_slider .column")[1].clone(true));
  /*
  var innerText = $$("#team_slider .column")[0].innerHTML;
  var newelt = new Element("div", {'class':'column'});
  newelt.update(innerText);
  $("team_slider").appendChild(newelt);

  innerText = $$("#team_slider .column")[1].innerHTML;
  newelt = new Element("div", {'class':'column'});
  newelt.update(innerText);
  $("team_slider").appendChild(newelt);
  */
}

function about_prev_page(evt) {
  Event.stop(evt);
  if (about_page_animation_inprogress) return false;

  var elt = $('team_slider');
  var docw = $('content').getWidth();
  var curpage = Math.floor(-parseInt(elt.getStyle('left'))/docw)+1;
  var totalpages = Math.ceil($$("#team_slider .column").length / 2);

  var margin = parseInt($$("#team_slider .column")[0].getStyle("margin-right"));

  if (curpage<=1) {
    var loopto = -(docw+margin)*(totalpages-1)+"px";
    //elt.setStyle({left:loopto});
    curpage = totalpages;
  }

  var nextpage = curpage-1;
  var newleft = -(docw+margin)*(nextpage-1);
  newleft += 'px';
  about_page_animation_inprogress = true;
  var switch_delay = about_active_panel!=null ? 0.3 : 0;
  if (about_active_panel!=null) {
    about_close_panel(about_active_panel, loopto);
  } else {
    if (loopto!=undefined)  elt.setStyle({'left':loopto});
  }
  new Effect.Morph(elt, {style:'left:'+newleft, duration: 1, delay: switch_delay, afterFinish: function() {
    about_page_animation_inprogress = false;
  }
  });
}
function about_next_page(evt) {
  Event.stop(evt);
  if (about_page_animation_inprogress) return false;

  var elt = $('team_slider');
  var docw = $('content').getWidth();
  var curpage = Math.floor(-parseInt(elt.getStyle('left'))/docw)+1;
  var totalpages = Math.ceil($$("#team_slider .column").length / 2);
  var loopto = undefined;

  if (curpage>=totalpages) {
    //looping
    loopto = "0px";
    curpage = 1;
  }

  var margin = parseInt($$("#team_slider .column")[0].getStyle("margin-right"));
  var nextpage = curpage+1;
  var newleft = -(docw+margin)*(nextpage-1);
  newleft += 'px';
  about_page_animation_inprogress = true;
  var switch_delay = about_active_panel!=null ? 0.3 : 0;
  if (about_active_panel!=null) {
    about_close_panel(about_active_panel, loopto);
  } else {
    if (loopto!=undefined)  elt.setStyle({left:loopto});
  }
  new Effect.Morph(elt, {style:'left:'+newleft, duration: 1, delay: switch_delay, afterFinish: function() {
    about_page_animation_inprogress = false;
  }
  });
}

function about_click_dispatch(evt) {
  var target = evt.element();
  if (target.tagName.toLowerCase()=='img' && target.className=='arr' ||
	  target.tagName.toLowerCase()=='span' && target.className=='arrow' ||
      target.tagName.toLowerCase()=='span' && target.className=='close' ||
      target.tagName.toLowerCase()=='a' && target.className=='name') {
    Event.stop(evt);
    if (about_active_panel==null || target.up('div.item')!=about_active_panel) {
      about_open_panel(target.up('div.item'));
    } else {
      about_close_panel(target.up('div.item'));
    }
  }
}

function about_open_panel(elt) {
  if (animation_in_progress) return false;

  if (about_active_panel!=null) {
    about_next_panel = elt;
    about_close_panel(about_active_panel);
    return false;
  }

  animation_in_progress = true;

  about_active_panel = elt;
  about_next_panel = null;

  var arrow_elt = elt.down('span.arrow');
  var close_elt = elt.down('span.close');
  var dots_elt = elt.down('span.dots');
  var extra_content_elt = elt.down('span.info');
  var profile_elt = elt.down('div.profile');
  var profile_p = elt.down('div.profile p');
  var photos_elt = elt.down('div.photos');

  arrow_elt.hide();
  close_elt.setStyle({display:'inline'});

  var prev_height = profile_p.getHeight()+"px";

  dots_elt.hide();
  extra_content_elt.setOpacity(0);
  extra_content_elt.setStyle({display:'inline'});

  var new_height = profile_p.getHeight()+"px";

  profile_p.setStyle({height:prev_height});
  profile_p.prev_height = prev_height;

  //photos_elt.setOpacity(0);
  photos_elt.setStyle({display:'block', top:'0px'});
  var idx = 1;
  Element.childElements(photos_elt).reverse().each(function(elt) {
    elt.absolutize();
    var orig_top = elt.getStyle('top');
    elt.setStyle({top:"-120px", 'z-index':(10+idx)});
    new Effect.Morph(elt, {style: "top:"+orig_top, delay: 1, duration: 0.5 });
    idx++;
  });

  new Effect.Morph(profile_p, {style:"height:"+new_height, afterFinish: function() {
    animation_in_progress = false;
  }
  });
  if (Prototype.Browser.IE) {
	new Effect.Opacity(extra_content_elt, {from: 1, to: 1});
  } else {
  	new Effect.Opacity(extra_content_elt, {from: 0, to: 1});
  }
  
}
function about_close_panel(elt, loopto, newcurpage) {
  if (animation_in_progress) return false;

  animation_in_progress = true;

  var arrow_elt = elt.down('span.arrow');
  var close_elt = elt.down('span.close');
  var dots_elt = elt.down('span.dots');
  var extra_content_elt = elt.down('span.info');
  var profile_elt = elt.down('div.profile');
  var profile_p = elt.down('div.profile p');
  var photos_elt = elt.down('div.photos');

  arrow_elt.show();
  close_elt.hide();

  new Effect.Morph(photos_elt, {style: "top: -355px", duration: 0.25});

  var new_height = profile_p.prev_height;
  new Effect.Morph(profile_p, {style:"height:"+new_height, duration: 0.3, afterFinish: function() {
    if (loopto!=undefined) {
      $("team_slider").setStyle({left:loopto});
    }

    dots_elt.show();
    extra_content_elt.hide();
    profile_p.setStyle({height:'auto'});
    about_active_panel = null;
    animation_in_progress = false;
    if (about_next_panel!=null) {
      about_open_panel(about_next_panel);
    }
  }.bind(this)
  });

  if (Prototype.Browser.IE) {
	new Effect.Opacity(extra_content_elt, {from: 1, to: 1, duration: 0.3});
  } else {
  	new Effect.Opacity(extra_content_elt, {from: 1, to: 0, duration: 0.3});
  }

}

//------------------------------------------------------- CONTACT

function contact_init() {
  document.observe("dom:loaded", contact_wire);
}

function contact_wire() {
  $$('#map_holder .rolloverable').each(function(elt) {
    elt.observe("mouseover", contact_map_rollover);
    elt.observe("mouseout", contact_map_rollout);
  });

  //initting form
  $("contact_form").observe("submit", contact_onsubmit);
  $("submit_but").observe("click", contact_onsubmit);
}

function contact_map_rollover(evt) {
  var elt = evt.element();
  var overelt = elt.up('.rolloverable').down('.over');
  elt.up('.rolloverable').setStyle({'z-index':'100'});
  overelt.setOpacity(0)
  overelt.setStyle({display:'block'});
  overelt.eff = new Effect.Opacity(overelt, {from: 0, to: 1, duration: 0.3});
}
function contact_map_rollout(evt) {
  var elt = evt.element();
  elt.up('.rolloverable').down('.over').hide();
  elt.up('.rolloverable').setStyle({'z-index':'0'});
}

var email_regexp = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/i;

function contact_onsubmit(evt) {
  //checking entry
  Event.stop(evt);

  if (contact_field_empty('entry_name')) {
    contact_show_errorpane("Please make sure you fill all required fields, which we marked in red for you.");
    return false;
  }
  if (contact_field_empty('entry_email') && contact_field_empty('entry_phone')) {
    contact_show_errorpane("Please enter either phone number or email, so that we have means contacting you.");
    return false;
  }

  if (!contact_field_empty('entry_email')) {
    if (!$('entry_email').value.match(email_regexp)) {
      contact_show_errorpane("You have entered an email address, but it doesn't seem to have the correct format. Please check again.")
      return false;
    }
  }

  if (contact_field_empty('entry_message')) {
    contact_show_errorpane("Please enter a message for us!");
    return false;
  }

  $$('#contact_form label').each(function(elt) {
    elt.removeClassName('required');
  })

  //if we're fine until now, trying to send the mail
  new Effect.BlindUp('errors', {duration: 0.3});
  new Ajax.Request(
      'index.html', {
        parameters: $('contact_form').serialize(true),
        onFailure: function() {
          contact_show_errorpane("There was an error submitting your input. Please try again.")
        },
        onSuccess: function() {
          contact_onsuccess()
        }
      }
  );

}

function contact_field_empty(field_id) {
  return ($(field_id).value.trim()=='');
}

function contact_show_errorpane(msg) {
  //showing error fields

  if (contact_field_empty('entry_name')) {
    $('label_name').addClassName('required');
  } else {
    $('label_name').removeClassName('required');
  }

  if (contact_field_empty('entry_email') && contact_field_empty('entry_phone')) {
    $('label_email').addClassName('required');
    $('label_phone').addClassName('required');
  } else {
    if (!contact_field_empty('entry_email') || !contact_field_empty('entry_phone')) {
      $('label_email').removeClassName('required');
      $('label_phone').removeClassName('required');
    }
  }

  if (!contact_field_empty('entry_email')) {
    if (!$('entry_email').value.match(email_regexp)) {
      $('label_email').addClassName('required');
    } else {
      $('label_email').removeClassName('required');
    }
  }

  if (contact_field_empty('entry_message')) {
    $('label_message').addClassName('required');
  } else {
    $('label_message').removeClassName('required');
  }


  $('errors').update(msg);
  if (!$('errors').visible()) {
    new Effect.BlindDown('errors', {duration: 0.5});
	if (!Prototype.Browser.IE) {
    	new Effect.Pulsate('errors', {delay: 0.5, from: 0.2, duration: 3});
	}
  } else {
	if (!Prototype.Browser.IE) {
    	new Effect.Pulsate('errors', {from: 0.2, duration: 3});
	}
  }
}

function contact_onsuccess() {
  new Effect.BlindUp('contact_form', {duration: 0.7});
  $('form_thanks').setOpacity(0);
  new Effect.BlindDown('form_thanks', {duration: 1, delay: 1});
  new Effect.Opacity('form_thanks', {from: 0, to: 1, duration: 1, delay: 1});
}


///=========================================== Tweening stuff
// Bounce (adapted from “EaseOutBounce”)
Effect.Transitions.Bounce = function(pos) {
  if (pos < (1/2.75)) {
    return (7.5625*pos*pos);
  } else if (pos < (2/2.75)) {
    return (7.5625*(pos-=(1.5/2.75))*pos + .75);
  } else if (pos < (2.5/2.75)) {
    return (7.5625*(pos-=(2.25/2.75))*pos + .9375);
  } else {
    return (7.5625*(pos-=(2.625/2.75))*pos + .984375);
  }
};
// BouncePast (new creation based on “EaseOutBounce”)
Effect.Transitions.BouncePast = function(pos) {
  if (pos < (1/2.75)) {
    return (7.5625*pos*pos);
  } else if (pos < (2/2.75)) {
    return 2 - (7.5625*(pos-=(1.5/2.75))*pos + .75);
  } else if (pos < (2.5/2.75)) {
    return 2 - (7.5625*(pos-=(2.25/2.75))*pos + .9375);
  } else {
    return 2 - (7.5625*(pos-=(2.625/2.75))*pos + .984375);
  }
};

//adding trim functionality for IE
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

function isTouchDevice() {
    try {
        document.createEvent("TouchEvent");
        return true;
    } catch (e) {
        return false;
    }
}
