// general.js
function initAll()
{
    selectURL();
    makeSortable();
}

function selectURL()
{
    if( $('shortened-output') )
    {
        $('shortened-output').select();
    }
}

function search()
{
    if( $('search-term').value != '' )
    {
        window.location.href = '/search/all/' + $('search-term').value;
    }
}

function toggleMoreSocial()
{
    $('more-link').blur();
    
    if( $('social-more').style.display == 'none' )
    {
        $('social-more').style.display = 'block'
        $('more-link').innerHTML = 'less';
    }
    else
    {
        $('social-more').style.display = 'none'
        $('more-link').innerHTML = 'more';
    }
    
    // Due to conflicting technologies, this is handled above.
    // Sortable needs floats, but Slide needs inlines...  Gah.
    // Effect.toggle('social-more','slide');
}

function makeSortable()
{
    if( $('socials') )
    {
        Sortable.create('socials', {handle: 'handle', containment: ['socials','socials-more'], overlap: 'horizontal', constraint: 'horizontal', dropOnEmpty: true, onUpdate: function(){ saveSocialOrder( Sortable.serialize('socials',{name:'favorites'}) ); } } );
    }
    
    if( $('socials-more') )
    {
        Sortable.create('socials-more', {handle: 'handle', containment: ['socials','socials-more'], overlap: 'horizontal', constraint: 'horizontal', dropOnEmpty: true, onUpdate: function(){ saveSocialOrder( Sortable.serialize('socials-more',{name:'more'}) ); } } );
    }
}

function saveSocialOrder( theOrderData )
{
    new Ajax.Request(
        '/share/save_order', {
            method: 'post',
            asynchronous: false,
            parameters: theOrderData            
    });
}

function toggleAlwaysPreview( alwaysPreview, reload )
{
    new Ajax.Request( '/zeus/always_preview/' + alwaysPreview, {
        method: 'get',
        onComplete: function(){
            if( reload && reload == 'true' )
            {
                window.location.reload();
            }
        }
    });
    
}

function viewMap( mapId )
{
    // Load the map
    
    if( $('yahoomap').innerHTML == '&nbsp;Loading...' )
    {
        new Ajax.Request('/tracking/display_map/' + mapId, {
            method: 'get'
        });
    }
    
    // Show it
    new Effect.toggle( 'yahoomap-slider', 'Slide' );
}

function createYahooMarker(geopoint, size, theLabel) { 
    var myImage = new YImage();
    myImage.src = '/images/mapmarker.gif';
    myImage.size = new YSize(size, size);
    var marker = new YMarker(geopoint, myImage);
    marker.addAutoExpand('Visitors');
    
    var markerMarkup = theLabel;  
              
    YEvent.Capture(marker, EventsList.MouseClick,   
        function(){  
            marker.openSmartWindow(markerMarkup);  
    });  
    
    return marker; 
}

// nicetitle.js
Event.observe(window, "load", makeNiceTitles);

var XHTMLNS = "http://www.w3.org/1999/xhtml";
var CURRENT_NICE_TITLE;
var browser = new Browser();

function makeNiceTitles() {
    if (!document.createElement || !document.getElementsByTagName) return;
    // add namespace methods to HTML DOM; this makes the script work in both
    // HTML and XML contexts.
    if(!document.createElementNS)
    {
        document.createElementNS = function(ns,elt) {
            return document.createElement(elt);
        }
    }

    if( !document.links )
    {
        document.links = document.getElementsByTagName("a");
    }
    for (var ti=0;ti<document.links.length;ti++) {
        var lnk = document.links[ti];
        if (lnk.title) {
            lnk.setAttribute("nicetitle",lnk.title);
            lnk.removeAttribute("title");
            Event.observe(lnk,"mouseover",showNiceTitle);
            Event.observe(lnk,"mouseout",hideNiceTitle);
            Event.observe(lnk,"focus",showNiceTitle);
            Event.observe(lnk,"blur",hideNiceTitle);
        }
    }
    var instags = document.getElementsByTagName("ins");
    if (instags) {
    for (var ti=0;ti<instags.length;ti++) {
        var instag = instags[ti];
        if (instag.dateTime) {
            var strDate = instag.dateTime;
            var dtIns = new Date(strDate.substring(0,4),parseInt(strDate.substring(4,6)-1),strDate.substring(6,8),strDate.substring(9,11),strDate.substring(11,13),strDate.substring(13,15));
            instag.setAttribute("nicetitle","Added on "+dtIns.toString());
            Event.observe(instag,"mouseover",showNiceTitle);
            Event.observe(instag,"mouseout",hideNiceTitle);
            Event.observe(instag,"focus",showNiceTitle);
            Event.observe(instag,"blur",hideNiceTitle);
        }
    }
    }
}

function findPosition( oLink ) {
  if( oLink.offsetParent ) {
    for( var posX = 0, posY = 0; oLink.offsetParent; oLink = oLink.offsetParent ) {
      posX += oLink.offsetLeft;
      posY += oLink.offsetTop;
    }
    return [ posX, posY ];
  } else {
    return [ oLink.x, oLink.y ];
  }
}

function showNiceTitle(e) {
    if (CURRENT_NICE_TITLE) hideNiceTitle(CURRENT_NICE_TITLE);
    if (!document.getElementsByTagName) return;
    if (window.event && window.event.srcElement) {
        lnk = window.event.srcElement
    } else if (e && e.target) {
        lnk = e.target
    }
    if (!lnk) return;
    if (lnk.nodeName.toUpperCase() != 'A') {
        // lnk is not actually the link -- ascend parents until we hit a link
        lnk = getParent(lnk,"A");
    }
    if (!lnk) return;

    if( browser.isIE == false )
    {
        if( lnk.hasClassName('show-nice-title') == false ) return;
    }
    else if( lnk.getAttribute('class') != 'show-nice-title' )
    {
        return;
    }

    nicetitle = lnk.getAttribute("nicetitle");
    
    var d = document.createElementNS(XHTMLNS,"div");
    d.className = "nicetitle";
    tnt = document.createTextNode(nicetitle);
    pat = document.createElementNS(XHTMLNS,"p");
    pat.className = "titletext";
    pat.appendChild(tnt);
    d.appendChild(pat);
//    if (lnk.href) {
//        tnd = document.createTextNode(lnk.href);
//        pad = document.createElementNS(XHTMLNS,"p");
//        pad.className = "destination";
//        pad.appendChild(tnd);
//        d.appendChild(pad);
//    }
    
    STD_WIDTH = 80;
    if (lnk.href) {
//        h = lnk.href.length;
        h = nicetitle.length;
    } else { h = nicetitle.length; }
    if (nicetitle.length) {
      t = nicetitle.length;
    }
    h_pixels = h*8; t_pixels = t*10;
    
    if (h_pixels > STD_WIDTH) {
        w = h_pixels;
    } else if ((STD_WIDTH>t_pixels) && (t_pixels>h_pixels)) {
        w = t_pixels;
    } else if ((STD_WIDTH>t_pixels) && (h_pixels>t_pixels)) {
        w = h_pixels;
    } else {
        w = STD_WIDTH;
    }
        
    d.style.width = w + 'px';    

    /*
    mx = lnk.offsetLeft;
    my = lnk.offsetTop;
    */
    mpos = findPosition(lnk);
    mx = mpos[0];
    my = mpos[1];
    //xy = getMousePosition(e);
    //mx = xy[0]; my = xy[1];
    
    d.style.left = (mx+15) + 'px';
    d.style.top = (my+15) + 'px';
    if (window.innerWidth && ((mx+w) > window.innerWidth)) {
        d.style.left = (window.innerWidth - w - 25) + "px";
    }
    if (document.body.scrollWidth && ((mx+w) > document.body.scrollWidth)) {
        d.style.left = (document.body.scrollWidth - w - 25) + "px";
    }
    
    document.getElementsByTagName("body")[0].appendChild(d);
    
    CURRENT_NICE_TITLE = d;
}

function hideNiceTitle(e) {
    if (!document.getElementsByTagName) return;
    if (CURRENT_NICE_TITLE) {
        document.getElementsByTagName("body")[0].removeChild(CURRENT_NICE_TITLE);
        CURRENT_NICE_TITLE = null;
    }
}

// Add an eventListener to browsers that can do it somehow.
// Originally by the amazing Scott Andrew.
//function addEvent(obj, evType, fn){
//  if (obj.addEventListener){
//    obj.addEventListener(evType, fn, false);
//    return true;
//  } else if (obj.attachEvent){
//	var r = obj.attachEvent("on"+evType, fn);
//    return r;
//  } else {
//	return false;
//  }
//}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}

function getMousePosition(event) {
  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }
  return [x,y];
}

// Determine browser and version.

function Browser() {
// blah, browser detect, but mouse-position stuff doesn't work any other way
  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

// lightbox.js
/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
*/

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

Event.observe(window, "load", initialize);
Event.observe(window, "load", getBrowserInfo);
Event.observe(window, "unload", Event.unloadCache);

var lightbox = Class.create();

lightbox.prototype = {

	yPos : 0,
	xPos : 0,

	initialize: function(ctrl) {
        
        if ($('lbOnAuto')) {
            var lbOnAuto = $('lbOnAuto').value; 
            if (lbOnAuto) {
                this.content = lbOnAuto;
                if (browser == 'Internet Explorer'){
                    this.getScroll();
                    this.prepareIE('2600px', 'scroll');
                    this.setScroll(0,0);
                    this.hideSelects('hidden');
                }
                this.displayLightbox("block");
                $('lbOnAuto').value = '';
            } 
        }
        
        this.content = ctrl.href;
		Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
		ctrl.onclick = function(){return false;};
	},
	
	// Turn everything on - mainly the IE fixes
	activate: function(){
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('100%', 'hidden');
			this.setScroll(0,0);
			this.hideSelects('hidden');
		}
		this.displayLightbox("block");
	},
	
	// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
	prepareIE: function(height, overflow){
		bod = document.getElementsByTagName('body')[0];
		bod.style.height = height;
		bod.style.overflow = overflow;
  
		htm = document.getElementsByTagName('html')[0];
		htm.style.height = height;
		htm.style.overflow = overflow; 
	},
	
	// In IE, select elements hover on top of the lightbox
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},
	
	// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	getScroll: function(){
		if (self.pageYOffset) {
			this.yPos = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){
			this.yPos = document.documentElement.scrollTop; 
		} else if (document.body) {
			this.yPos = document.body.scrollTop;
		}
	},
	
	setScroll: function(x, y){
		window.scrollTo(x, y); 
	},
	
	displayLightbox: function(display){
		$('overlay').style.display = display;
		$('lightbox').style.display = display;
		if(display != 'none') this.loadInfo();
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
		var myAjax = new Ajax.Request(
        this.content,
        {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		);
		
	},
	
	// Display Ajax response
	processInfo: function(response){
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		new Insertion.Before($('lbLoadMessage'), info)
		$('lightbox').className = "done";	
		this.actions();			
	},
	
	// Search through new links within the lightbox, and attach click event
	actions: function(){
		lbActions = document.getElementsByClassName('lbAction');

		for(i = 0; i < lbActions.length; i++) {
			Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
			lbActions[i].onclick = function(){return false;};
		}

	},
	
	// Example of creating your own functionality once lightbox is initiated
	insert: function(e){
        link = Event.element(e);
        Element.remove($('lbContent'));
        
        var myAjax = new Ajax.Request(
            link.href,
            {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
            );    
    },
	
	// Example of creating your own functionality once lightbox is initiated
	deactivate: function(){
		Element.remove($('lbContent'));
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
		}
		
		this.displayLightbox("none");
	}
}

/*-----------------------------------------------------------------------------------------------*/

// Onload, make all links that need to trigger a lightbox active
function initialize(){
	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new lightbox(lbox[i]);
	}
}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
	overlay.id		= 'overlay';
	lb					= document.createElement('div');
	lb.id				= 'lightbox';
	lb.className 	= 'loading';
	lb.innerHTML	= '<div id="lbLoadMessage">' +
						  '<p>Loading</p>' +
						  '</div>';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}
