/*-------------------------------GLOBAL VARIABLES------------------------------------*/
var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;
var is_loaded = 0;

Event.observe(window, 'load', initialize, false);
Event.observe(window, 'load', getBrowserInfo, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var newdev_lightbox = Class.create();

newdev_lightbox.prototype = {

	yPos : 0,
	xPos : 0,
    tab : 0,
    atag: 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');
				}
                else {
                    this.getScroll();
					this.setScroll(0, 0);
                }
				this.displayLightbox("block");
				$('lbOnAuto').value = '';
			}
		}
		
		this.atag = ctrl;
		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() {
        this.content = this.atag.href;
		if (browser == 'Internet Explorer'){
			this.getScroll();
			this.prepareIE('2600px', 'scroll');
			this.setScroll(0,0);
			this.hideSelects('hidden');
            this.hideFlash('hidden');
		}
        else {
            this.getScroll();
	     	this.setScroll(0, 0);
			
        }
		this.displayLightbox("block");
	},
	
	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; 
	},
	
	hideSelects: function(visibility){
		selects = document.getElementsByTagName('select');
		for(i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}
	},

    hideFlash: function(visibility) {
        embeds = document.getElementsByTagName('embed');
        for(i = 0; i < embeds.length; i++) {
            embeds[i].style.visibility = visibility;
        }
    },

	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){
        if ($('newdev_overlay') == null) {
            initialize();
        }
		$('newdev_overlay').style.display = display;
		$('newdev_lightbox').style.display = display;
		if (display != 'none' && is_loaded == 0) {
                   is_loaded = 1;
                   this.loadInfo();
                }
	},
	
	// Begin Ajax request based off of the href of the clicked linked
	loadInfo: function() {
        var url = this.content;
		var myAjax = new Ajax.Request( url,
                                       {
                                        method: 'get', 
                                        onSuccess: this.processInfo.bindAsEventListener(this),
                                        onException: function(req,exception) { 
                                             /* what do we do?! 
                                              * For now...lets pretend nothing happended 
                                              */
                                           }
                                       }
		);
	},
	
	// Display Ajax response
	processInfo: function(response) {
		info = "<div id='lbContent'>" + response.responseText + "</div>";
		new Insertion.Before($('lbLoadMessage'), info)
		$('newdev_lightbox').className = "done";	
		this.actions();

        var head = document.getElementsByTagName("head")[0];
        link = document.createElement('link');
        link.rel = "stylesheet";
        link.href = "/" + new_developments_folder + "/css/nd.css.php?building_id=" + $( 'ms_building_id' ).value ;
        link.type = "text/css";
        head.appendChild( link );
    },
	
	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;};
		}
	},
	
	insert: function(e){
	   link = Event.element(e).parentNode;
	   Element.remove($('lbContent'));

	   var myAjax = new Ajax.Request( link.href,
			                          {method: 'get', parameters: "", asynchronous: false, evalJS: 'force', onComplete: this.processInfo.bindAsEventListener(this)}
	   );
	 
	},

    insertContent: function( e ) {
        link = Event.element(e);

        var id = link.id.charAt(6);
        this.tab = id;

        for( x = 1; x < 17; x++ )
        {
            var outer_tab  = document.getElementById( 'ms_mt' + x );
            var inner_tab  = document.getElementById( 'ms_mt2' + x );

            if( ! outer_tab ) continue;

            if( x != id )
            {
	            outer_tab.setAttribute( 'class', 'microsite_menu_tab' );
		        outer_tab.setAttribute( 'className', 'microsite_menu_tab' );
                inner_tab.setAttribute( 'class', '' );
                inner_tab.setAttribute( 'className', '' );
            }
            else
            {
                outer_tab.setAttribute( 'class', 'microsite_menu_tab_on' );
		        outer_tab.setAttribute( 'className', 'microsite_menu_tab_on' );
                inner_tab.setAttribute( 'class', 'microsite_menu_tab_on1' );
                inner_tab.setAttribute( 'className', 'microsite_menu_tab_on1' );
            }
        }        
	    var myAjax = new Ajax.Request(
			  link.href,
			  {method: 'get', parameters: "", asynchronous: true, evalJS: 'force', onComplete: this.processContent.bindAsEventListener(this)}
	    );
    },

    processContent: function(response) {
        var content = document.getElementById( 'microsite_content' );
        
        for( var i = 0; i < content.childNodes.length; i++ )
        {
            var childNode = content.childNodes[i];
            content.removeChild( childNode );
        }

        content.innerHTML = response.responseText;
        eval( 'msTab' + this.tab + '();' );

        if( typeof( urchinTracker ) == 'function' ) {
            urchinTracker( $( 'ms_google_url' ).value + 'Tab' + this.tab  );
        }
    },

	deactivate: function(){
                is_loaded = 0;
		Element.remove($('lbContent'));
		
		if (browser == "Internet Explorer"){
			this.setScroll(0,this.yPos);
			this.prepareIE("auto", "auto");
			this.hideSelects("visible");
            this.hideFlash("visible");
		}

		this.displayLightbox("none");
        if ( location.href.indexOf('pmicrosite.php') != -1) {
            window.location="/new_developments/";
        }
	}   
}

/*-----------------------------------------------------------------------------------------------*/

function initialize(){
	addLightboxMarkup();
	lbox = document.getElementsByClassName('lbOn');
	for(i = 0; i < lbox.length; i++) {
		valid = new newdev_lightbox(lbox[i]);
	}
}

function detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

function addLightboxMarkup() {

    if (window.new_developments_host === undefined) return;
    
	bod 				= document.getElementsByTagName('body')[0];
	overlay 			= document.createElement('div');
    overlay.id		    = 'newdev_overlay';
    d                   = detectMacXFF();

    if( d )
    {
        overlay.style.opacity = 1;
        overlay.style.background = "transparent url(" + new_developments_host +"/" + new_developments_folder +"/images/overlay.png) repeat scroll 0%";
    }

	lb					= document.createElement('div');
	lb.id				= 'newdev_lightbox';
	lb.className 	    = 'newdev_loading';
	lb.innerHTML	    = '<div id="lbLoadMessage"><img src="' + new_developments_host +'/' + new_developments_folder + '/images/loading.gif"/></div>';
	bod.appendChild(overlay);
	bod.appendChild(lb);
}

function LoadScript( src )
{
    var doc = document.getElementsByTagName( 'head' ).item( 0 );
    var js = document.createElement( 'script' )
    js.setAttribute( 'type', 'text/javascript' );
    js.setAttribute( 'src', src );
    doc.appendChild( js ); 
}

function msTab1() 
{
    if( typeof( Prototype ) == 'undefined' )
    {
        LoadScript( 'http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6' );    
    }
}

function msTab2() {}

function msTab3() {}

function msTab4() {}

function msTab5() 
{
    var map = new VEMap( 'google_map' );
    latlong = new VELatLong( $('ms_latitude').value, $('ms_longitude').value );
    map.LoadMap( latlong, 16, 'r', false );
    var shape = new VEShape( VEShapeType.Pushpin, [ latlong ] );
    shape.SetCustomIcon( '/' + new_developments_folder + '/images/b_icon.gif' );
    map.AddShape( shape );
}

function msTab6() { msGallery( 1 ); }

function msGallery( img )
{
    if( img == -1 )
    {
        img = $( 'ms_gc' ).value;
        img--;
    }
    
    if( img == -2 )
    {
        img = $( 'ms_gc' ).value;
        img++;
    }

    if( img == 1 && $( 'ms_gl' ).value == 1 )
    {
        $( 'ms_gp' ).style.display = 'none';
        $( 'ms_gn' ).style.display = 'none';
        $( 'ms_gb' ).style.display = 'none';   
    }
    else if( img == 1 )
    {
        $( 'ms_gp' ).style.display = 'none';
        $( 'ms_gn' ).style.display = 'inline';
        $( 'ms_gb' ).style.display = 'none';
    }
    else if( img == $( 'ms_gl' ).value )
    {
        $( 'ms_gp' ).style.display = 'inline';
        $( 'ms_gn' ).style.display = 'none';
        $( 'ms_gb' ).style.display = 'none';
    } 
    else
    {
        $( 'ms_gp' ).style.display = 'inline';
        $( 'ms_gn' ).style.display = 'inline';
        $( 'ms_gb' ).style.display = 'inline';
    }    

    $( 'ms_gc' ).value = img;
    $( 'ms_gt').innerHTML = $( 'ms_gt' + img ).value;

    $( 'ms_g' ).src = $( 'ms_g' + img ).src.replace( '_thumb', '' );
}

function validate_form( form ) {
	var msg = new String( form.msg.value );
	if ( form.fname.value == "" )
	{
		alert( "Please fill in your first name" );
		form.fname.focus();
		return false;
	}
	if ( form.lname.value == "" )
	{
		alert( "Please fill in your last name" );
		form.lname.focus();
		return false;
	}
	if ( form.email.value == "" )
	{
		alert( "Please fill in your E-Mail address" );
		form.email.focus();
		return false;
	}
	if ( form.dayphone.value == "" )
	{
		alert( "Please enter your day time phone number" );
		form.dayphone.focus();
		return false;
	}
	if ( msg.length >= 1000 )
	{
		alert( "Message is too long!\nPlease shorten your message");
		form.msg.focus();
		return false;
	}
	if ( form.min_price.value == "" ||
	     form.min_price.value == "$" )
	{
		alert( "Please enter a value for the minimum price" ) ;
		form.min_price.focus() ;
		return false ;
	}
	if ( form.max_price.value == "" ||
	     form.max_price.value == "$" )
	{
		alert( "Please enter a value for the maximum price" ) ;
		form.max_price.focus() ;
		return false ;
	}
	if ( parseInt(form.max_price.value) < parseInt(form.min_price.value) )
	{
		alert( "Please enter a maximum price greater than your minimum" ) ;
		form.max_price.focus() ;
		return false ;
	}
    return true;
}

function contactRequest( building_name ) 
{
    if( ! validate_form( $( 'frmContact' ) ) )
        return false;

    msg = "<p>Thank you for contacting CityRealty concerning the purchase of an apartment at "  + building_name + ". <br/> We will contact you soon to discuss your needs in greater detail. <br/> If you would like immediate assistance, please call us at <strong>212.755.5544.</strong>";

    new Ajax.Request( "/contact/building/confirmation.php", {
        parameters : Form.serialize( $( 'frmContact' ) ),
        onSuccess : function( t, j ) { $( 'microsite_contact' ).innerHTML = msg; }
    });

    return false;
}

/*-----------------------------------------------------------------------------------------------*/

//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;
}

