/**
 * Javascript Library []
 * Created By: Joshua Hetland
 */

document.observe("dom:loaded", function(){
	fetchSponsors();
	externalLinks();
});

var jSponsors;

var iCounter1 = 0;
var iCounter2 = 0;
var iCounter3 = 0;
var iCounter4 = 0;

var myInterval1;
var myInterval2;
var myInterval3;
var myInterval4;

function fetchSponsors(){
	new Ajax.Request('./lib/php/getsponsors.php', {
		onComplete: function(transport){
			jSponsors = transport.responseText.evalJSON();

      //process tall logos
      if(jSponsors[1].length > 0){

        $('sponsor_link1').style.display = 'block';
        switchSponsor1();
        myInterval1 = setInterval("switchSponsor1()",16500);
      }

      //process short logos
      if(jSponsors[2].length > 0){
        $('sponsors').style.display = 'block';
        $('sponsor_link2').style.display = 'block';
        switchSponsor2();
        myInterval2 = setInterval("switchSponsor2()",15000);
        if(jSponsors[2].length > 2){
          $('sponsor_link3').style.display = 'block';
          $('sponsor_link4').style.display = 'block';
          iCounter3 = Math.round((jSponsors[2].length -1) / 2);
          iCounter4 = jSponsors[2].length -1;
          switchSponsor3();
          switchSponsor4();
          myInterval3 = setInterval("switchSponsor3()",16000);
          myInterval4 = setInterval("switchSponsor4()",15500);
        }//end if jSponsors[2].length > 2
      }//end if jSponsors[2].length > 0
		}//end onComplete
	});
}

function switchSponsor1(){
	var sponsorImg1 = $('sponsor_banner1');
	var sponsorAnchor1 = $('sponsor_link1');
	if(iCounter1 == jSponsors[1].length){
		iCounter1 = 0;
	}
    sponsorImg1.style.display = 'inline';
    new Effect.Opacity(sponsorImg1, {from: 1, to: 0,	duration: 0}, {queue: {position: 'end', scope: 'switchSponsor1'}});
	  sponsorImg1.src = jSponsors[1][iCounter1]['logo'];
	  sponsorImg1.alt = jSponsors[1][iCounter1]['name'];
	  sponsorImg1.title = jSponsors[1][iCounter1]['name'];
	  sponsorAnchor1.href = jSponsors[1][iCounter1]['url'];
    sponsorAnchor1.rev = jSponsors[1][iCounter1]['id'];
    new Effect.Opacity(sponsorImg1, {from: 0, to: 1,	duration: 1}, {queue: {position: 'end', scope: 'switchSponsor1'}});
		iCounter1++;
}

function switchSponsor2(){
	var sponsorImg2 = $('sponsor_banner2');
	var sponsorAnchor2 = $('sponsor_link2');
	if(iCounter2 == jSponsors[2].length){
		iCounter2 = 0;
	}
  if (iCounter2 !== iCounter3 && (iCounter2 !== iCounter4)) {
    sponsorImg2.style.display = 'inline';
    new Effect.Opacity(sponsorImg2, {from: 1, to: 0,	duration: 0}, {queue: {position: 'end', scope: 'switchSponsor2'}});
	  sponsorImg2.src = jSponsors[2][iCounter2]['logo'];
	  sponsorImg2.alt = jSponsors[2][iCounter2]['name'];
	  sponsorImg2.title = jSponsors[2][iCounter2]['name'];
	  sponsorAnchor2.href = jSponsors[2][iCounter2]['url'];
    sponsorAnchor2.rev = jSponsors[2][iCounter2]['id'];
    new Effect.Opacity(sponsorImg2, {from: 0, to: 1,	duration: 1}, {queue: {position: 'end', scope: 'switchSponsor2'}});
		iCounter2++;
	}else {
		iCounter2++;
		switchSponsor2();
	}
}

function switchSponsor3(){
  var sponsorImg3 = $('sponsor_banner3');
  var sponsorAnchor3 = $('sponsor_link3');
  if(iCounter3 == jSponsors[2].length){
    iCounter3 = 0;
  }
	if (iCounter3 !== iCounter2 && (iCounter3 !== iCounter4)) {
  	sponsorImg3.style.display = 'inline';
  	new Effect.Opacity(sponsorImg3, {from: 1, to: 0,	duration: 0}, {queue: {position: 'end', scope: 'switchSponsor3'}});
  	//need some way to make this syncronous if it is not
			sponsorImg3.src = jSponsors[2][iCounter3]['logo'];
			sponsorImg3.alt = jSponsors[2][iCounter3]['name'];
			sponsorImg3.title = jSponsors[2][iCounter3]['name'];
			sponsorAnchor3.href = jSponsors[2][iCounter3]['url'];
			sponsorAnchor3.rev = jSponsors[2][iCounter3]['id'];
			new Effect.Opacity(sponsorImg3, {from: 0, to: 1,	duration: 1}, {queue: {position: 'end', scope: 'switchSponsor3'}});
			iCounter3++;
		}else{
			iCounter3++;
			switchSponsor3();
		}
  
}

function switchSponsor4(){
  var sponsorImg4 = $('sponsor_banner4');
  var sponsorAnchor4 = $('sponsor_link4');
  if(iCounter4 == jSponsors[2].length){
    iCounter4 = 0;
  }
	if (iCounter4 !== iCounter2 && (iCounter4 !== iCounter3)) {
  	sponsorImg4.style.display = 'inline';
  	new Effect.Opacity(sponsorImg4, {from: 1, to: 0,	duration: 0}, {queue: {position: 'end', scope: 'switchSponsor4'}});
  	//need some way to make this syncronous if it is not
			sponsorImg4.src = jSponsors[2][iCounter4]['logo'];
			sponsorImg4.alt = jSponsors[2][iCounter4]['name'];
			sponsorImg4.title = jSponsors[2][iCounter4]['name'];
			sponsorAnchor4.href = jSponsors[2][iCounter4]['url'];
			sponsorAnchor4.rev = jSponsors[2][iCounter4]['id'];
			new Effect.Opacity(sponsorImg4, {from: 0,	to: 1, duration: 1}, {queue: {position: 'end', scope: 'switchSponsor4'}});
			iCounter4++;
		} else {
			iCounter4++;
			switchSponsor4();
		}
  
}

function trackClicks(oThis){
	//record the sponsor that was clicked for tracking purposes
	new Ajax.Request('./lib/php/tracksponsors.php', {
		method: 'post',
		parameters: {
		  sponsor_id: oThis.rev
	}
	});
}

function externalLinks() {   
 if (!document.getElementsByTagName) return;   
 var anchors = document.getElementsByTagName("a");   
 for (var i=0; i<anchors.length; i++) {   
   var anchor = anchors[i];   
   if (anchor.getAttribute("href") &&   
       anchor.getAttribute("rel") == "external")   
     anchor.target = "_blank";   
 }   
}   

function showMailinglistBox(oThis){
  //get the position of the element
  var iOffsetPosition = findLoc(oThis);
  //iOffsetPosition.left = iOffsetPosition.left + (oThis.offsetWidth / 2);
  iOffsetPosition.top = iOffsetPosition.top + (oThis.offsetHeight);
  //alert("Width: " + oThis.offsetWidth + " Height: " + oThis.offsetHeight );
  //alert("Center of Element: Top-" + iOffsetPosition.top + " Left-" + iOffsetPosition.left);

  //create overlay for page that will close elements on click
  var oOverlay = document.createElement('div');
  oOverlay.setAttribute('id','mailinglist_overlay');
  oOverlay.setAttribute('onclick',"removeElements(['mailinglist_overlay','mailinglist_box']);");
  //oOverlay.onclick = removeElements({div1:'overlay_div',div2:'mailinglist_div']);

  document.body.appendChild(oOverlay);

  //will need to compute the center of the element being made as well to center it
  var oMailinglistDiv = document.createElement('div');
  //sStyles = "top: " + iOffsetPosition.top + "px; left: " + iOffsetPosition.left + "px;";
  //oMailinglistDiv.setAttribute('style',sStyles);
  oMailinglistDiv.setAttribute('id','mailinglist_box');
  oMailinglistDiv.style.top = iOffsetPosition.top + 'px';
  oMailinglistDiv.style.left = iOffsetPosition.left + 'px';
  oMailinglistDiv.style.zIndex = '101';

  var sInnerHTML = '<h3>Join The SU Mailing List</h3>';
  sInnerHTML += '<p>Enter your e-mail address and receive updates about this, and other Salmon Unlimited events.</p>';
  sInnerHTML += '<input id="email_input" type="text" onkeypress="acceptEnterKey(event,submitEmail,\'email_input\')" />';
  sInnerHTML += '<input id="email_submit" type="button" value="Submit" onclick="submitEmail(\'email_input\')" />';
  sInnerHTML += '<div id="submit_message"></div>';
  //oMailinglistDiv.innerHTML = sInnerHTML;

  document.body.appendChild(oMailinglistDiv); //attach the mailinglist div to the document and grow it
  var iEndHeight = 180;
  var iEndWidth = 300;
  var iNewTop = (iOffsetPosition.top - iEndHeight < 10)? 10 : (iOffsetPosition.top - iEndHeight);
  var iNewLeft = iOffsetPosition.left; //(iOffsetPosition.left - (iEndWidth / 2) < 10)? 10 : (iOffsetPosition.left - (iEndWidth / 2));
  new Effect.Morph(oMailinglistDiv, {
    style: {
      top: iNewTop + 'px',
      left: iNewLeft + 'px',
      width: iEndWidth + 'px',
      height: iEndHeight + 'px'
    },
    duration: .2,
    afterFinish: function(){
      oMailinglistDiv.innerHTML = sInnerHTML;
      oMailinglistDiv.style.height = 'auto'; //setting it to auto allows it to reflow if needed
      //alert(oMailinglistDiv.offsetHeight);
      $('email_input').focus();
    }
  });
}//end showMailinglistBox

function submitEmail(sInputName) {
	if ($(sInputName).value !== "") {
  	new Ajax.Request('./lib/php/join_mailinglist.php', {
  		method: 'post',
  		parameters: {
				direct_join: true,
  			email: $(sInputName).value
  		},
  		onComplete: function(transport){ //check if it was valid and added or not
					var json = transport.responseText.evalJSON();
					if (json.valid && (json.success)) {
            $('submit_message').style.color = '#128424';
            $('submit_message').innerHTML = 'Thank you! Your address has been added.';
            setTimeout('removeElements([\'mailinglist_overlay\',\'mailinglist_box\'])', 2000);
					}else{ //display a message and send focus to the text box and select the contents
            $('submit_message').style.color = '#d42b2b';
            $('submit_message').innerHTML = 'Invalid E-mail address, please try again.';
						$('email_input').focus();
						$('email_input').select();
					}//end if valid && success
				}//end onComplete
			});//end Ajax.Request
		}//end if value !== ""
}//end function submitEmail()

function findLoc(oElement){
  var iPosLeft = 0;
  var iPosTop = 0;
  if(oElement.offsetParent){
    do{
      iPosLeft += oElement.offsetLeft;
      iPosTop += oElement.offsetTop;
    }while(oElement = oElement.offsetParent);
  }//end if
  return {left:iPosLeft,top:iPosTop};
}//end findLoc

//argument is a list of element names to be removed from the dom
function removeElements(sElements){
  for(var i in sElements){
    if(sElements.hasOwnProperty(i)){
      $(sElements[i]).parentNode.removeChild($(sElements[i]));
    }//end hasOwnProperty
  }//end for in
}//end removeElements()

function acceptEnterKey(eEvent,oFunction,oParameter){
  if(eEvent.keyCode === 13){
    //this will pass anything along to the function specified by oFunction provided in oParameters, which could be an array of information or a simple string
    oFunction(oParameter);
  }//end if keyCode = Enter
}//end acceptEnterKey()

//creates an overlay above the content section of the page (header and nav are both still accessable)
function setWaiting(sParent){
  var oOverlay = document.createElement('div');
  oOverlay.setAttribute('id','waiting_overlay');
  //oOverlay.setAttribute('onclick',"unsetWaiting();"); //used to unset in testing
  if(typeof(sParent) == 'undefined'){
    document.body.appendChild(oOverlay);
  }else{
    $(sParent).appendChild(oOverlay);
  }
}

//removes the waiting overlay from the content section of the page
function unsetWaiting(sParent){
  $('waiting_overlay').parentNode.removeChild($('waiting_overlay'));
}