/**
* global javascript for Preston Bailey
* $Id$
*/

var $pbj = jQuery.noConflict();

var pb_global = {
init: function() {
  this.sender_nameMessage = 'Please enter your name';
  this.recipient_nameMessage = 'Please enter your friend\'s name';
  this.sender_emailMessage = 'Please enter your email address';
  this.recipient_emailMessage = 'Please enter your friend\'s email address';
  this.newsletter_fnameMessage = 'Please enter your first name';
  this.newsletter_lnameMessage = 'Please enter your last name';
  this.newsletter_emailMessage = 'Please enter your email';
  this.sendToFriendURL = '/wp-content/themes/preston-2.0/tell-a-friend.php';
  this.newsletterURL = '/wp-content/themes/preston-2.0/newsletter-signup.php';
  this.setWindowHeight();
  if ($pbj("#main-content-container").hasClass('flash-container-true')) {
    pb_global.fixHomeFlashPosition();
    if ($pbj("#main-flash-container").hasClass('gallery-flash-container')) {
      growFlash();
    } else {
      shrinkFlash();
    }
  }
},
setWindowHeight: function() {
  var windowHeight = $pbj(window).height();
  var documentHeight = $pbj(document).height();
  if (documentHeight > windowHeight) { finalHeight = documentHeight; } else { finalHeight = windowHeight; }
  $pbj('#page-wrapper').css('height', finalHeight); 
},
fixIE6TopNav: function() {
  $pbj('#top-nav-block').css('position','relative');
  var navOffset = $pbj('#top-nav-block').position().top;
  $pbj('#top-nav-block').css('margin-top','-' + navOffset);
},
fixHomeFlashPosition: function() {
  var mainFlashPos = $pbj('#main-flash-container').offset();
  $pbj('#flash-content-container').css('top',mainFlashPos.top);
  $pbj('#flash-content-container').css('left',mainFlashPos.left);

},
showOverlay: function(ID,obj) {
      
  //Get the screen height and width  
  var maskHeight = $pbj(document).height();  
  var maskWidth = $pbj(window).width();  

  //Set height and width to mask to fill up the whole screen  
  $pbj('#mask').css({'width':maskWidth,'height':maskHeight});  
    
  //transition effect       
  $pbj('#mask').fadeIn(500);      

  // try to get offset
  if (obj) {
  var zoffset = $pbj(obj).offset();
    var zoffsetTop = zoffset.top;
  } else {
    var zoffsetTop = 0;
  }
  //Get the window height and width  
  var winH = $pbj(window).height();  
  var winW = $pbj(window).width();  
          
  // put the iframe behind the content for IE6
  $pbj('#overlay-iframe').css('width',$pbj('#'+ID).width());
  // hack the height for IE6
  $pbj('#overlay-iframe').css('height','450px');
  $pbj('#overlay-iframe').css('top',  (winH+zoffsetTop)/2-$pbj('#'+ID).height()/2);
  $pbj('#overlay-iframe').css('left', winW/2-$pbj('#'+ID).width()/2);  

  //Set the popup window to center  
  $pbj('#'+ID).css('top',  (winH+zoffsetTop)/2-$pbj('#'+ID).height()/2);  
  $pbj('#'+ID).css('left', winW/2-$pbj('#'+ID).width()/2);  

  $pbj('#mask').fadeTo("fast",0.5,function() {
    $pbj('#'+ID).css('display','block');
  });    
    $pbj('#overlay-iframe').css('display','block');
       
},
showNewsletterSignup: function(obj) {
  $pbj("#overlay-content").load(this.newsletterURL);
  if (obj) {
    this.showOverlay('overlay-content',obj);
  } else {
    this.showOverlay('overlay-content');
  }
  Metrics.trackPageView('/mailing-list/');
},
postNewsletterSignup: function() {
  this.hideError();
  this.checkNewsletterFields();
  if (this.error == true) {
  } else {
    var data = this.processNewsletterFields();
    $pbj.post(this.newsletterURL,data,function(response) {
      $pbj('#overlay-content').html(response);
    },'html');
    Metrics.trackNewsletterSignup();
  }
},
newsletterClose: function() {
  this.hideOverlay('overlay-content');
  Metrics.trackEvent('form','close','newsletter signup');
},
showSendToFriend: function() {
  $pbj("#overlay-content").load(this.sendToFriendURL);
  this.showOverlay('overlay-content');
  Metrics.trackPageView('/tell-a-friend/');
},
sendToFriendClose: function() {
  this.hideOverlay('overlay-content');
  Metrics.trackEvent('form','close','send to friend');
},
postSendToFriend: function() {
  this.hideError();
  // check forms
  this.checkFields();
  if (this.error == true) {
  } else {
    var data = this.processFields();
    $pbj.post(this.sendToFriendURL,data,function(response) {
      $pbj('#overlay-content').html(response);
    },'html');
    Metrics.trackEvent('form','submit','send to friend');
  }
},
processFields: function() {
  var data = {'sender_name':$pbj('#sender_name').val(), 'sender_email':$pbj('#sender_email').val(), 'recipient_name':$pbj('#recipient_name').val(), 'recipient_email':$pbj('#recipient_email').val(), 'message':$pbj('#message').val(), 'url': document.location.href};
  return data;
},
processNewsletterFields: function() {
  var data = {'newsletter_fname':$pbj('#newsletter_fname').val(), 'newsletter_lname':$pbj('#newsletter_lname').val(), 'newsletter_email':$pbj('#newsletter_email').val(), 'newsletter_promos':$pbj('#newsletter_promos:checked').val(), 'newsletter_optin':$pbj('#newsletter_optin:checked').val()};
  return data;
},
checkNewsletterFields: function() {
  this.error = false;
  if (this.validateEmpty('newsletter_fname') == false) { this.error = true; this.presentError('newsletter_fname', this.newsletter_fnameMessage);}
  if ($pbj('#newsletter_fname').val() == this.newsletter_fnameMessage) { this.error = true; this.presentError('newsletter_fname', this.newsletter_fnameMessage);}
  if (this.validateEmpty('newsletter_lname') == false) { this.error = true; this.presentError('newsletter_lname', this.newsletter_lnameMessage);}
  if ($pbj('#newsletter_lname').val() == this.newsletter_lnameMessage) { this.error = true; this.presentError('newsletter_lname', this.newsletter_lnameMessage);}
  if (this.validateEmail('newsletter_email') == false) { this.error = true; this.presentError('newsletter_email', this.newsletter_emailMessage);}
  if ($pbj('#newsletter_email').val() == this.newsletter_emailMessage) { this.error = true; this.presentError('newsletter_email', this.newsletter_emailMessage);}
  if (this.validateCheckBox('newsletter_optin') == false) { this.error = true; this.presentError('newsletter_optin','');}
},
checkFields: function() {
  this.error = false;
  // check sender name
  if (this.validateEmpty('sender_name') == false) { this.error = true; this.presentError('sender_name',this.sender_nameMessage);}
  if ($pbj('#sender_name').val() == this.sender_nameMessage) { this.error = true; this.presentError('sender_name',this.sender_nameMessage);}
  // check sender email
  if (this.validateEmail('sender_email') == false) { this.error = true; this.presentError('sender_email',this.sender_emailMessage);}
  if ($pbj('#sender_email').val() == this.sender_emailMessage) { this.error = true; this.presentError('sender_email',this.sender_emailMessage);}
  // check recipient  name
  if (this.validateEmpty('recipient_name') == false) { this.error = true; this.presentError('recipient_name',this.recipient_nameMessage);}
  if ($pbj('#recipient_name').val() == this.recipient_nameMessage) { this.error = true; this.presentError('recipient_name',this.recipient_nameMessage);}
  // check recpient email
  if (this.validateEmail('recipient_email') == false) { this.error = true; this.presentError('recipient_email',this.recipient_emailMessage);}
  if ($pbj('#recipient_email').val() == this.recipient_emailMessage) { this.error = true; this.presentError('recipient_email',this.recipient_emailMessage);}
},
presentError: function(ID,MESSAGE) {
  $pbj('#'+ID + '-row > .check-arrow').css('visibility','visible');
  if ($pbj('#'+ID).attr('type') == 'text') {
    this.displayErrorMessage(MESSAGE,ID);
    $pbj('#'+ID).bind('focus',function() {
      if (this.value == MESSAGE) {this.value = ''};
    });
  }
},
displayErrorMessage: function(MESSAGE,ID) {
  $pbj('#'+ID).addClass('error-message');
  $pbj('#'+ID).val(MESSAGE);
},
validateEmpty: function(ID) {
  var testobj = $pbj.trim($pbj('#'+ID).val());
  if (testobj.length < 1) {
    return false;
  }
  else {
    return true;
  }
},
validateEmail: function(ID) {
  if (this.validateEmpty(ID) == false) {return false;}
  else {
    var value = $pbj('#'+ID).val();
    return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
  }
},
validateCheckBox: function(ID) {
  if ($pbj('#'+ID+':checked').val() == 'Y') {
    return true;
  } else {
    return false;
  }
},
hideError: function() {
  $pbj('.check-arrow').css('visibility','hidden');
  $pbj('.error-message').removeClass('error-message');
},
hideOverlay: function(ID) {
  $pbj('#mask').css('display','none');
  $pbj('#overlay-iframe').css('display','none');
  $pbj('#'+ID).css('display','none');
},
bookmark: function(url,title){
  Metrics.bookmark();
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  window.external.AddFavorite(url,title);
  } else if (navigator.appName == "Netscape") {
    window.sidebar.addPanel(title,url,"");
  } else {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
},
shareSocial: function(obj,type,url,title,message) {
  if (message) {
    this.message = message;
  } else {
    this.message = '';
  }
  obj.target = "_blank";
  switch(type) {
    case 'email':
      Metrics.favorite('email');
      if (this.message.length < 1) {
        this.message = 'I thought that you would like this site';
      }
      obj.href='mailto:?subject=' + escape(title) + '&body=' + escape(this.message) + ':%0A%0A[' + escape(url) + ']';
    break;
    case 'digg':
      Metrics.favorite('digg');
      obj.href = 'http://digg.com/submit?phase=2&url=' + escape(url) + '&title=' + escape(title);
    break;
    case 'twitter':
      Metrics.favorite('twitter');
	url = this.tweetThis(obj,url,message);
 //     obj.href = 'http://twitter.com/prestonrbailey';
    break;
    case 'myspace':
      Metrics.favorite('myspace');
      obj.href = 'http://www.myspace.com/Modules/PostTo/Pages/?l=3&u=' + escape(url) + '&t=' + escape(title) + '&c=';
    break;
    case 'facebook':
      Metrics.favorite('facebook');
      obj.href = 'http://www.facebook.com/sharer.php?u=' + escape(url) + '&t=' + escape(title);
    break;
  } // end switch
},
tweetThis: function(obj,url,message) {
  if (message) {
    this.message = message;
  } else {
    this.message = 'Interesting page from Preston Bailey';
  }
  // first, get the shortURL
  //var tinyurl = '/wp-content/themes/preston-2.0/tinyurl.php';
  var bitly = '/wp-content/themes/preston-2.0/bitly.php';
  var rresponse = $pbj.ajax({'type':'GET', 'url':bitly,'data':({'url': url}),'dataType':'json','async':false}).responseText;
  var rresponse_json = eval('('+rresponse+')');
  var short_url = rresponse_json['results'][document.location.href]['shortUrl'];
  // put the whole url together 
  twitter_url = 'http://twitter.com/home?source=prestonrbailey&status=' + escape(this.message) + ':+'+short_url;
  obj.href=twitter_url;
  return twitter_url;
},

jumpToArchive:function(obj) {
	var url = $pbj('#archive_form option:selected').val();
	if(url != null && url != '') {
		mlink = Metrics.replaceURL(url);
		Metrics.trackEvent('blog','archive',mlink);
		window.location.href = url;
	}
},
jumpToLink:function(obj) {
	var url = $pbj('#link_form option:selected').val();
	if(url != null && url != '') {
		mlink = Metrics.replaceURL(url);
		Metrics.trackEvent('blog','links',mlink);
		Metrics.exit(mlink);
		window.open(url);
	}
},
activateNewsLetterSignup: function(obj) {
  if ($pbj('#newsletter_emaila').val() != 'Enter your email address') {
    var t = setTimeout('newsletterEmailSet()',1000);
  } 
  if (obj) {
    this.showNewsletterSignup(obj);
  } else {
    this.showNewsletterSignup();
  }
},
zzz: function() {}
};



function newsletterEmailSet() {
    $pbj('#newsletter_email').val($pbj('#newsletter_emaila').val());
}

function growFlash() {
  $pbj("#before_after").css('width','970px');
  $pbj("#before_after").css('height','505px');

  var section = getGallerySection();
  Metrics.sliderExpand(section);
}

function shrinkFlash() {
  if ($pbj("#main-flash-container").hasClass('gallery-flash-container')) {
  } else {
  $pbj("#before_after").css('width','650px');
  $pbj("#before_after").css('height','394px');

  var section = getGallerySection();
  Metrics.sliderShrink(section);
  }
}

function getNavSection() {
  var section = 'home';
  switch (document.location.pathname) {
   case '/portfolio/before-after/':
     section = 'before-after';
    turnNavOn(section);
   break;
   case '/portfolio/events/':
     section = 'events';
    turnNavOn(section);
   break;
   case '/portfolio/table-settings/':
     section = 'table-settings';
    turnNavOn(section);
   break;
   case '/portfolio/artistry/':
     section = 'artistry';
    turnNavOn(section);
   break;
   case '/portfolio/media/':
     section = 'media';
    turnNavOn(section);
   break;
   case '/portfolio/biography/':
     section = 'about';
    turnNavOn(section);
   break;
   case '/inspiration/books-invitations/':
     section = 'books-inv';
    turnNavOn(section);
   break;
   case '/inspiration/how-tos/':
     section = 'how-to';
    turnNavOn(section);
   break;
   default:
     section = 'home';
   break;
  }
}

function turnNavOn(section) {
  $pbj('.col.' + section).addClass('on');
}

function trackImage(URL) {
  // first, figure out where we are
  current = document.location.pathname
  if (current.length < 2) {
    current = '/home/';
  }
  distilled_url = Metrics.replaceURL(URL);
  image_url = Metrics.removeHostname(distilled_url);
  final_url = '/gallery-slide/view' + current + image_url;
  final_url = final_url.replace(/\/\//,'/');
  Metrics.trackPageView(final_url);
}
function goUrl(URL) {
  document.location.href = URL;
}

$pbj(document).ready(function() { pb_global.init();});
$pbj(window).bind('resize', function() { pb_global.setWindowHeight();});

function ImageSlider(id) {
  var timer;
  var currpos = 0;
  var slideWindow = $pbj('#' + id + ' .slide-window')[0];
  var slideul = $pbj('#' + id + ' ul')[0];
  var lis = $pbj('#' + id + ' ul li');
  var totalWidth = lis.length * imageWidth;
  //var slideMax = slideWindow.offsetWidth;
  var slideMax = totalWidth - 420 ;

  // bind actions
  $pbj('#' + id + ' .right-button').mouseover( function() {
        timer = setInterval( function() {
            if ( currpos < slideMax) {
                currpos += 10;
                slideul.style.left = -1 * currpos + 'px';
            }
        },speed);
  });
  $pbj('#' + id + ' .left-button').mouseover( function() {
        timer = setInterval( function() {
            if ( currpos > 0) {
                currpos -= 10;
                slideul.style.left = -1 * currpos + 'px';
            }
        },speed);
  });
  $pbj('#' + id + ' .slider-button').mouseout( function() {
        clearInterval(timer);
  });

  return {
    totalWidth: totalWidth,
    slideMax: slideMax
  }

}
function contactPopup() {
  var contactWin = window.open('/general-contact-popup/','contact-win','width=700,height=600');
}
