// JavaScript Document
/**
 * Resize comparison table container element
 * 
 * Intelligently resize comparison table container to allow for
 * proper styling in not-so-intelligent browsers. I am Jack's
 * complete lack of surprise.
 * 
 * Options currently supported:
 *     sponsored : number,
 *     free : number
 * 
 * Note: because this directly maniuplates the Document Object
 * Model, this function should only ever be executed after page
 * load/"DOM ready".
 * 
 * @param {Object} selector jQuery selector expression for selecting
 *                          the container element
 * @param {Object} options  Object used to specify necessary values
 *                          used for resizing calculations
 * @param {Object} minWidth Minimum width the container element
 *                          should resize to
 * @return {Object} jQuery
 */
 
jQuery.smartResize = function( selector, options, minWidth )
{
    var options = jQuery.extend({
            sponsored: 0,
            free: 0
        }, options),
        result = (options.sponsored*167)            //Calculate width of sponsored cells
                +(options.free*134)                 //Calculate width of free listing cells
                +(options.sponsored+options.free)   //Take into account cellpadding
                +2                                  //Left and right borders
                +235,                               //"Key" cell width
        minWidth = minWidth || 1000;

    jQuery(selector).css(
        "width",
        (result < minWidth ? minWidth : result)+"px"
    );
    
    return jQuery;
};

/**
 * Automatically create row togglers
 * 
 * Traverse the DOM and match/bind elements based on options
 * expressions to create the toggle up/down effect.
 * 
 * Options currently supported:
 *     eachExpression : string,
 *     arrowClassToggle: string
 *     
 * Note: because this directly maniuplates the Document Object
 * Model, this function should only ever be executed after page
 * load/"DOM ready".
 * 
 * @param {Object} options Object used to specify jQuery selector
 *                         patterns that match associating DOM
 *                         elements
 * @return {Object} jQuery
 */
jQuery.createRowTogglers = function ( options )
{
    var options = jQuery.extend({
            eachExpression : "tr.heading td.heading div",
            arrowClassToggle : "contract"
        }, options),
        iterator = function( i, el )
        {
            jQuery(el).click(function()
            {
                var index = i*2;
           
                jQuery( 'div.table.content:nth(' + index + ')' ).slideToggle();
                jQuery( 'div.table.content:nth(' + ++index + ')' ).slideToggle();
                jQuery(this).toggleClass( options.arrowClassToggle );
            });
        };
    
    jQuery(options.eachExpression).each(iterator);
    
    return jQuery;
};

/**
 * Create popups
 * 
 * Traverse the DOM - based on options - and match/bind/style
 * elements according to their hierarchy in relation to popups. This
 * function handles the popup elements and their activators.
 * 
 * Currently supported options:
 *     eachExpression : string,
 *     togglerExpression : string,
 *     popupExpression : string
 *     
 * Note: because this directly maniuplates the Document Object
 * Model, this function should only ever be executed after page
 * load/"DOM ready".
 * 
 * @param {Object} options
 * @return {Object} jQuery
 */

jQuery.createPopups = function ( options )
{
    var options = jQuery.extend({
            eachExpression : "span.has-popup",
            togglerExpression : "a",
            popupExpression : "p"
        }, options),
        iterator = function( i, el )
        {
            if ( jQuery( el ).attr("__bound_to_popup") != undefined )
                return;

            var popup = $(
                '<div class="popup"><div class="top"></div><div class="content">'+
                jQuery( el ).find( options.popupExpression ).html() +
                '</div><div class="bottom"></div></div>');
            popup.appendTo("body");

            jQuery( el )
            .find( options.togglerExpression )
            .mouseover(function(){
                var offset = jQuery( this ).offset();
                
                popup.stop( true, true ).css({
                    left: offset.left-(popup.width()/2)+(jQuery( this ).width()/2),
                    top: offset.top-(popup.height())
                }).fadeIn();
            })
            .mouseout(function(){
                popup.stop( true, true ).fadeOut();
            });
            
            popup
            .mouseover(function(){
                jQuery( this )
                .stop( true, true )
                .css("display", "block");
            })
            .mouseout(function(){
                jQuery( this )
                .stop( true, true )
                .fadeOut();
            });
            
            // Initially hide popups
            jQuery( el )
            .find( options.popupExpression )
            .css({display:"none"});
        };
    jQuery( options.eachExpression ).each( iterator );    
    return jQuery;
};

var Pages = {};
Pages.compare = function( queryObject )
{
    jQuery( document ).ready(function(){
        jQuery
        .createPopups()
        .smartResize( "div.container", queryObject, 1000 )
        .createRowTogglers();
    });    
};
Pages.list = function( queryObject )
{
    jQuery( document ).ready(function(){
        jQuery
        .createPopups({
            eachExpression : "span.has-popup.p-popup",
            togglerExpression : "img.help",
            popupExpression : "p"
        })
        .createPopups({
            eachExpression : "span.has-popup.span-popup",
            togglerExpression : "a.help",
            popupExpression : "span"
        })
        .createPopups({
            eachExpression : "span.has-popup.easy-popup",
            togglerExpression : "span.help",
            popupExpression : "p"
        });
    });
};

Pages.form = function( queryObject )
{
    jQuery( document ).ready(function(){
        jQuery
        .createPopups({
            eachExpression : "span.has-popup",
            togglerExpression : "a",
            popupExpression : "span"
        })
		.createRowTogglers()
		.createPopups({
            eachExpression : "span.has-popup-preview",
            togglerExpression : "a",
            popupExpression : "p"
        })
		.createPopups({
            eachExpression : "span.has-popup-preview-notes",
            togglerExpression : "a",
            popupExpression : "p"
        });
    });
};

$(function(){
	el = $("span.has-popup-preview-notes:first").html();
	$('.popup_content').each(function () {
		$(this).html($(this).attr('rel'));
	});
})

Pages.profile = function( queryObject )
{
    $(function () {
        jQuery.createRowTogglers().createPopups();
		
		var setVideoFramePosition = function () {
			var bodywidth = $(window).width();
			var bodyheight = $(window).height();
			var framewidth = $('#videoframe').outerWidth();	
			var frameheight = $('#videoframe').outerHeight();
			var scrolltop = $(window).scrollTop();
			
			$('#videoframe').css('left', (bodywidth - framewidth) / 2);
			$('#videoframe').css('top', scrolltop + ((bodyheight - frameheight) / 2));
			$('.ui-widget-overlay').css('top', $(window).scrollTop() + 'px');
		};		
		
		$('.sidevideolink').click(function (e) {
			e.preventDefault();
			
			if ($('#videoframe').length > 0) {
				$('#videoframe').remove();
				$('.ui-widget-overlay').remove();
				$(window).unbind('scroll', setVideoFramePosition);
			}
			
			var code = $(this).attr('href').split('#')[1];
			
			var frame = $('<div id="videoframe" class="floating" />');
			var closebuttonwrap = $('<div id="closevideoframewrap" />');
			var closebutton = $('<a id="closevideoframe" href="#">close (x)</a>');
			var iframewrap = $('<div id="videoiframewrap" />');
			var caption = $('<p id="s_caption" />');
			var clear = $('<div class="clear" />');
			
			if ($(this).attr('title') != '') caption.html($(this).attr('title'));
			
			closebutton.click(function (e) {
				e.preventDefault();
				if ($('#videoframe').length > 0) {
					$('#videoframe').remove();
					$('.ui-widget-overlay').remove();
					$(window).unbind('scroll', setVideoFramePosition);
					window.location.href = '#' + self.document.location.hash.substring(1).split(',')[0];
				}
			});
			
			closebuttonwrap.append(closebutton);
			frame.append(closebuttonwrap).append(iframewrap).append(caption).append(clear);
			$('body').append(frame);
			
			var overlay = $('<div class="ui-widget-overlay">');
			overlay.appendTo('body');
			
			var videourl = ''; var width = 540; var height = 340;
			if ($(this).hasClass('videotype_youtube')) {
				videourl = 'http://www.youtube.com/embed/' + code;
			} else if ($(this).hasClass('videotype_custom')) {
				videourl = '/biz/profiles/getvideo/' + code;
				width = 570;
				
				if ($(this).attr('vwidth') != 0)
					width = $(this).attr('vwidth');
					
				if ($(this).attr('vheight') != 0)
					height = $(this).attr('vheight');
			}
			
			frame.css('width', width);
			
			var iframe = $('<iframe id="s_video" width="' + width + '" height="' + height + '" src="' + videourl + '" frameborder="0" allowfullscreen></iframe>');
			iframewrap.append(iframe);
			
			setVideoFramePosition();
			$(window).bind('scroll', setVideoFramePosition);
			
			var video_id = $(this).attr('id').split('-')[1];
			if (typeof logvideo == 'function') {
				logvideo(video_id);
			}
			
			var hash = self.document.location.hash.substring(1).split(',')[0];
			hash = hash + ',video:' + video_id;
			window.location.href = '#' + hash;
		});
		

        $('#ListingMap').hide().jmap('init', {"mapShowjMapsIcon": false});
      
	    var load_map_bounds = new GLatLngBounds();
	  
        // Format our search query
        var address_query = $('.address1').text()+" "+$('.address2').text()+", "+$('.location').text();
		var is_first = true;        
		if (address_query != ', ') {
			$('#ListingMap').jmap('SearchAddress', {
				'query': address_query,
				'returnType': 'getLocations'
			  }, function(result, options) {
				var valid = Mapifies.SearchCode(result.Status.code);
				if (valid.success) {
				  var point = result.Placemark[0];
				  $('#ListingMap').jmap('AddMarker',{
					'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
					'pointHTML':address_query
				  }).show();
				  	load_map_bounds.extend(new GLatLng(point.Point.coordinates[1], point.Point.coordinates[0]));
				  	load_map_bounds.extend(new GLatLng(point.Point.coordinates[1] + 0.005, point.Point.coordinates[0] + 0.005));
				  	load_map_bounds.extend(new GLatLng(point.Point.coordinates[1] - 0.005, point.Point.coordinates[0] - 0.005));
			
					var centre = load_map_bounds.getCenter();
					
					if (is_first) {
						zoomix = 11;						
					} else {
						var zoomix = Mapifies.MapObjects['ListingMap'].getBoundsZoomLevel(load_map_bounds);
						if (zoomix > 11) zoomix = 11;
					}
					
					$('#ListingMap').jmap('CheckResize').jmap('MoveTo', {'mapCenter': [centre.lat(), centre.lng()], 'mapZoom': zoomix});
					
					is_first = false;
				} else {
				 // alert(valid.message + " " + address_query);
				}
			  }
			);
		}
		
		$('.additional_address').each(function () {
			var addaddress = $(this).find('.addaddress1').text()+" "+$(this).find('.addaddress2').text()+", "+$(this).find('.addlocation').text();
			$('#ListingMap').jmap('SearchAddress', {
				'query': addaddress,
				'returnType': 'getLocations'
			  }, function(result, options) {
				var valid = Mapifies.SearchCode(result.Status.code);
				if (valid.success) {
				  var point = result.Placemark[0];
				  $('#ListingMap').jmap('AddMarker',{
					'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
					'pointHTML':addaddress
				  }).show().jmap('CheckResize');
				  	load_map_bounds.extend(new GLatLng(point.Point.coordinates[1], point.Point.coordinates[0]));
				  	load_map_bounds.extend(new GLatLng(point.Point.coordinates[1] + 0.005, point.Point.coordinates[0] + 0.005));
				  	load_map_bounds.extend(new GLatLng(point.Point.coordinates[1] - 0.005, point.Point.coordinates[0] - 0.005));
				  
					var centre = load_map_bounds.getCenter();
					
					if (is_first) {
						zoomix = 11;						
					} else {
						var zoomix = Mapifies.MapObjects['ListingMap'].getBoundsZoomLevel(load_map_bounds);
						if (zoomix > 11) zoomix = 11;
					}
				
					$('#ListingMap').jmap('CheckResize').jmap('MoveTo', {'mapCenter': [centre.lat(), centre.lng()], 'mapZoom': zoomix});
					

					if (is_first) {
					  is_first = false;
					}
				} else {
				 // alert(valid.message + " " + addaddress + " x");
				}
			  }
			);
		});
    });
};

/**
 * Parse query string appended to "localprice.js" script include to allow for
 * custom runtime code execution on a page-by-page basis. Just remember to add
 * the "page" query paramater value to the Pages object.
 * 
 * Note: The Pages method (see example below) is always passed the translated
 * query object as its single only argument.
 * 
 */
$(function () {
    var params = [], pair, query = {}, url = [];
	
    if (url = jQuery('#lp-script').attr('rel'))  {
        for ( i = 0, params = url.split("&"), ln = params.length; i < ln; i++ ) {
            pair = params[i].split("=");
            query[pair[0]] = eval(pair[1]);
        }
    }
    
    if ( typeof query["page"] != "undefined" &&
         typeof Pages[query["page"]] == "function" )
         Pages[query["page"]]( query );
});
 
 
/* refine result secript */
function refineresult(id, type) {	
	var date = new Date();
    date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));

	if($('#section'+id).is(':visible')) {	
		$('#arrowimage'+id).attr("src",'/biz/img/grey_arrowleft.gif');	
   		$.cookie("refineresults_" + type + id, 'closed', {path: '/', expires: date});		
	} else  {
		$('#arrowimage'+id).attr("src",'/biz/img/grey_arrow.gif');
		$.cookie("refineresults_" + type + id, 'open', {path: '/', expires: date});
	}
	
	if (type == 'filter') $('.filters_container #section'+id).slideToggle();
	else $('.pricing_container #section'+id).slideToggle();
}
	
