/*******************************************/
// GLOBALS
/*******************************************/

//general information
var id = document.getElementById('id').value;
var slideshow_theme = document.getElementById('slideshow_theme').value;

//to process all the images
var images = new Array();
var image_count = document.getElementById('image_count').value;
for (var i = 1; i <= image_count; i++) {
	images[i] = new Array();
	images[i]['name'] = document.getElementById('form_image_' + i).name;
	images[i]['filename'] = '/vtsuite/v6/listing_files/' + id + '/' + document.getElementById('form_image_' + i).value;
	images[i]['x'] = document.getElementById('form_image_' + i + '_x').value;	
	images[i]['y'] = document.getElementById('form_image_' + i + '_y').value;
}

//google maps link
var map_link = document.getElementById('map_link');
var s1 = document.getElementById('address_1').value;
var c = document.getElementById('city').value;
var s = document.getElementById('state').value;

if (s1.length > 1 && c.length > 1 && s.length > 1) {

    s1 = encodeURIComponent(s1);
    //s1 = s1.replace(/\s/g, "+");
    c = c.replace(/\s/g, "+");
    s = s.replace(/\s/g, "+");

	var map_text = s1 + ",+" + c + ",+" + s;
    
    if (map_link != null) {
        map_link.innerHTML = "<a href='http://maps.google.com/?hl=en&q=" + map_text + "' target=\"_blank\" class='header_text'><img src=\"/vtsuite/v6/themes/" + slideshow_theme + "/location.jpg\" border=\"0\" alt='Property Location' /></a>";
    }
    
}

//used for dynamic image resizing
var available_x;
var available_y;
var use_x = 0;
var use_y = 0;
var current_image;
var old_image;
var allowed_to_render = true;

//banner
var banner_url = document.getElementById('person_slideshow_banner');
var banner_link_to = document.getElementById('person_url');
var banner = document.getElementById('banner_div');
var overridden_banner = document.getElementById('overridden_banner');
var overridden_banner_url = document.getElementById('overridden_banner_url');

if (overridden_banner != null) {
	banner_url = overridden_banner;
}

if (overridden_banner_url != null) {
	banner_link_to = document.getElementById('overridden_banner_url');
}

//slide divs
var img_holder = document.getElementById('img_div');

//general divs
var left = self.document.getElementById('left');
var contact_floater = self.document.getElementById('contact_floater');
var description_floater = self.document.getElementById('description_floater');
var resize_floater = self.document.getElementById('resize_floater');

//property information
var bedrooms = document.getElementById('bedrooms');
var bathrooms = document.getElementById('bathrooms');
var square_footage = document.getElementById('square_footage');
var lot_size = document.getElementById('lot_size');
var price = document.getElementById('price');

//audio
var audio_div = document.getElementById('audio_div');
var listing_audio = document.getElementById('slideshow_music');

//0 = off
//1 = running
//2 = paused
var ss_state = 0;

//0 = loading/not loaded
//1 = loaded
var ss_img_loaded = 0;

//0 = small
//1 = large
var size_state = 0;

//used to cancel the timer on pause
var mytime;

/*******************************************/
// EVENT HANDLERS
/*******************************************/

//called on thw window.onload event. start the slideshow.
function handle_onload() {

    var scenes = document.getElementById('scenes_div');
  
    for (var i = 1; i <= image_count; i++) {
		scenes.innerHTML = scenes.innerHTML + '<a class="item_text" id="scene_' + i + '" href="javascript: click_image(' + i + ');">' + images[i]['name'] + '</a>';
	}
 
	var first_image_link = document.getElementById('scene_1');
	if (first_image_link != null) {
		first_image_link.className = "active_item_text";
 	}

    current_image = 1;

	format_contact_info();
	
	format_description_info();

	show_banner();
	
	handle_audio(); 
    
    ss_start();
    
}

//called when the window.onresize event occurs.
//does not request any effects.
function handle_resize() {
    draw_slide(false);
}

/*******************************************/
// FUNCTIONS FOR THE SLIDESHOW IMAGE DISPLAY
/*******************************************/

//main function to process the transitions, updating, etc
//computers values of x and y to set the slide.
function draw_slide(show_effects) {

	if (image_count == 0) {
		return;
	}
	
	var header_y = document.getElementById('banner_div').offsetHeight;
	
	var proportion_x = images[current_image]['x'];
	var proportion_y = images[current_image]['y'];
	
	//get the x and y sizes of the window to see how much space is available to use.
	var x = 0;
	var y = 0;
	
	if (self.innerWidth) {
		x = self.innerWidth;
		y = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	} else if (document.body) {
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	} else {
		fatal_error();
	}

	//we will impose a minimum of how small the image can be.
	//using the x and y size of the window, determine how much we actually have free.
	//width = page width - width of leftmost div - small offset.	
	available_x = x - 174 - 20;
	
	//height = page height - banner height - small offset so the image doesn't run into the banner
	available_y = y  - header_y - 25;

	//set the image container to the available width. this will center the image.
	img_holder.style.width = available_x + 'px'; 	
	
	//compute the possible values of x and y that will keep the image in proportion.
	possible_x = Math.floor(available_x / proportion_x);
	possible_y = Math.floor(available_y / proportion_y);
			
	//set the images x and y to values that will keep it in proportion	
	if (possible_x > possible_y) {

		//if the height is the limiter
		var possible_x = Math.floor(available_y * (proportion_x / proportion_y));
		if (available_x < possible_x) {
			use_x = available_x;
		} else {
			use_x = possible_x;
		}
		use_y = available_y;

	} else {

		//width is limiter
		var possible_y = Math.floor(available_x * (proportion_y / proportion_x));
		if (available_y < possible_y) {
			use_y = available_y;
		} else {
			use_y = possible_y;
		}		
		use_x = available_x;			
		
	}

	//slide has nothing to do with the actual image. slide is the name given to whatever is shown on the screen (depends on window size, state, etc)

	//first, remove the existing slide if it's there.
	var old_slide = document.getElementById('current_slide');
	if (old_slide != null) {
		old_slide.id = 'slide_to_delete';
		old_slide.parentNode.removeChild(old_slide);
	}

	//now show the new one
	render_current_slide(show_effects);

}

//actually does the dom updating, effects, etc
function render_current_slide(show_effects) {

	//create the new slide.
	var new_slide = document.createElement('img');
	new_slide.id = 'current_slide';
	new_slide.src = images[current_image]['filename'] + '?' + Math.round((Math.random()*10000)+1);
	new_slide.width = use_x;
	new_slide.height = use_y;
	new_slide.alt = images[current_image]['name'];
	new_slide.style.backgroundColor = '#CCCCCC';

	img_holder.appendChild(new_slide);
	Event.observe('current_slide', 'load', ss_toggle_load); //god i love scriptaculous. this event observer actually works. normally. domelement.onLoad will fire as soon as it partially loads the image. this waits until the image is actually loaded.

	show_bottom_text();
	
	//2 ways to make the slide appear now that it's inserted into the DOM
	//1 - via an Effect (will callback after it's done updating)
	//2 - DHTML to set it to display
	if (show_effects && allowed_to_render) {
		allowed_to_render = false;	
		new_slide.style.display = 'none';
		Effect.Appear('current_slide',  { duration: 1, afterUpdate: render_slide_frame, afterFinish: render_complete_slide}); //afterUpdate will call the function to make the +- appear as soon as there is an offsetTop, etc to show
	} else {
        update_resize_floater(null);
        render_complete_slide(null);
		new_slide.style.display = '';
	}

}

//the slide has partially appeared on the page.
function render_slide_frame(effect) {

    update_resize_floater(effect);
    
}

//the slide has now fully appeard on screen
function render_complete_slide(effect) {
    
    //resize the text floaters if they are displayed
	if ((contact_floater != null) && (contact_floater.style.visibility == 'visible')) {
		show_contact_info();
	}
	if ((description_floater != null) && (description_floater.style.visibility == 'visible')) {
		show_description_info();
	}

}

//with some of the slide on the screen, we can now positions the +- enlarger over the displayed image.
function update_resize_floater(effect) {

	//IE will try and load the images for every single frame that occurs. only let it do it once.
	if (effect != null && effect.currentFrame > 1) {
		return;
	}

	var the_image = document.getElementById('current_slide');
	
	resize_floater.style.top = parseInt(the_image.offsetTop + 3) + 'px';
	resize_floater.style.left = parseInt(use_x + the_image.offsetLeft - 26) + 'px';

	if (size_state == 0) {
		resize_floater.innerHTML = "<img src='/vtsuite/v6/images/zoom_in.png' alt='Enlarge' onclick='toggle_size();' onmouseover=\"javascript: this.style.cursor='pointer';\" />";
	} else {
		resize_floater.innerHTML = "<img src='/vtsuite/v6/images/zoom_out.png' alt='Shrink' onclick='toggle_size();' onmouseover=\"javascript: this.style.cursor='pointer';\" />";
	}
	
	allowed_to_render = true;
	
}

function show_bottom_text() {
	
	var old_text = document.getElementById('text_holder');
	if (old_text != null) {
		old_text.parentNode.removeChild(old_text);
	}

	var the_image = document.getElementById('current_slide');

	var text_holder = document.createElement('div');

	text_holder.innerHTML = "<span class=\"room_name\">" + images[current_image]['name'] + "</span><span class=\"navigation\" id=\"image_navigation_text\"><a href=\"javascript:ss_prev();\">&lt;&lt;</a> <a href=\"javascript:ss_next();\">&gt;&gt;</a> </span>";
	text_holder.id = 'text_holder';

	text_holder.style.top = parseInt(the_image.offsetTop + the_image.clientHeight - 18) + 'px';

	img_holder.parentNode.appendChild(text_holder);

	text_holder.style.width = parseInt(the_image.width) + 'px';	
	text_holder.style.left = parseInt(the_image.offsetLeft + 4) + 'px';	

}


/*******************************************/
// SLIDESHOW CONTROLS
/*******************************************/

function ss_next() {

	ss_img_loaded = 0;

	old_image = current_image;

	if (current_image == image_count) {
		current_image = 1;
	} else {
		current_image++;
	}

	scroll_room_names(current_image);
	
	swap_active_links();

	draw_slide(true);
	
}

function ss_prev() {

	ss_img_loaded = 0;

	old_image = current_image;

	if (current_image == 1) {
		current_image = image_count;
	} else {
		current_image--;
	}

	scroll_room_names(current_image);

	swap_active_links();

	draw_slide(true);

}

function ss_start() {

	var button = document.getElementById('start_button');
	
	if (ss_state == 0) {
		button.src = '/vtsuite/v6/themes/' + slideshow_theme + '/pause.jpg';
		button.alt = 'Pause Slideshow';
		ss_state = 1;
	} else if (ss_state == 1) {
		clearTimeout(mytime);
		button.src = '/vtsuite/v6/themes/' + slideshow_theme + '/play.jpg';		
		button.alt = 'Start Slideshow';
		ss_state = 2;
		return;
	} else {
		button.src = '/vtsuite/v6/themes/' + slideshow_theme + '/pause.jpg';
		button.alt = 'Pause Slideshow';
		ss_state = 1;
	}
	
	mytime = setTimeout('run_ss()', 7000);

}

function run_ss() {

	if ((ss_state == 1) && (ss_img_loaded == 1)) {
		ss_next();
	} else {
		mytime = setTimeout('run_ss()', 7000);	
	}
	
}

function ss_toggle_load() {

	ss_img_loaded = 1;
		
	if (ss_state == 1) {
		//mytime could have been set from a previous call, so we need to unset it to prevent the 'hyper-skipping' effect
		clearTimeout(mytime);
		mytime = setTimeout('ss_next()', 7000);	
	}	
	
}

/*******************************************/
// ROOM LISTING
/*******************************************/

function click_image(which_image) {

	if (which_image == current_image) {
		return;
	}

	old_image = current_image;

	current_image = which_image;

	swap_active_links();
	
	draw_slide(true);

	return;

}

function swap_active_links() {

	if (image_count == 0) {
		return;
	}

	var old_image_link = document.getElementById('scene_' + old_image);
	if (old_image_link != null) {
		old_image_link.className = "item_text";
	}

	var current_image_link = document.getElementById('scene_' + current_image);
	current_image_link.className = "active_item_text";
	
}

function scroll_room_names(room) {

	var which_room = 'scene_' + room.toString();
	var point = document.getElementById(which_room).offsetTop;
	document.getElementById('scenes_div').scrollTop = point;

}

/*******************************************/
// FLOATING BOXES
/*******************************************/

// only one floater can be displayed at a time.
function show_contact_info() {

	if (contact_floater != null) {

		if (description_floater.style.visibility == 'visible') {
			hide_description_info();
		}

		var the_image = document.getElementById('current_slide');

        if (the_image != null) {
            var left_offset = the_image.offsetLeft;
            var top_offset = the_image.offsetTop;
        } else {
            var left_offset = 400;
            var top_offset = 100;
        }
        
		contact_floater.style.left =  parseInt(Math.floor(use_x / 2) - 217 + left_offset) + 'px';
		contact_floater.style.top = parseInt(Math.floor(use_y / 2) - 90 + top_offset) + 'px';
		contact_floater.style.visibility = 'visible';

	}
	
}

function hide_contact_info() {

	if (contact_floater != null) {
		contact_floater.style.visibility = 'hidden';
	}
	
}

function show_description_info() {

	if (description_floater != null) {

		if (contact_floater.style.visibility == 'visible') {
			hide_contact_info();
		}

		var the_image = document.getElementById('current_slide');

        if (the_image != null) {
            var left_offset = the_image.offsetLeft;
            var top_offset = the_image.offsetTop;
        } else {
            var left_offset = 400;
            var top_offset = 100;
        }
	
		description_floater.style.left =  parseInt(Math.floor(use_x / 2) - 217 + left_offset) + 'px';
		description_floater.style.top = parseInt(Math.floor(use_y / 2) - 90 + top_offset) + 'px';
		description_floater.style.visibility = 'visible';

	}
	
}

function hide_description_info() {

	if (description_floater != null) {
		description_floater.style.visibility = 'hidden';
	}
	
}

/*******************************************/
// SIZING FOR THE SLIDE, DISPLAY WINDOW, AND BANNER
/*******************************************/

//will expand the view of the image
//hides the banner, which should be enough, but some browsers will not put the links, buttons, all the way to the top.
//we must handle this.
function toggle_size() {

	if (size_state == 0) {
		size_state = 1;
		make_larger();
	} else {
		size_state = 0;
		make_smaller();
	}

}

function make_larger() {

	hide_banner();
	
	left.style.top = '0px';
	
}

function make_smaller() {
	
	show_banner();
	
	left.style.top = '100px';
			
}

function show_banner() {

	if ((banner_link_to.value != null) && (banner_link_to.value != '')) {
		banner.innerHTML = '<a href="' + banner_link_to.value + '" target="_blank"><img src="' + banner_url.value + '" class=\"banner_img\" alt="" /></a>';
	} else {
		banner.innerHTML = '<img src="' + banner_url.value + '" class=\"banner_img\" alt="" />';		
	}
	
	banner.style.height = '90px';
	banner.style.width = '100%';

	draw_slide(false);	

}

function hide_banner() {

	banner.innerHTML = '';
	banner.style.height = '0px';
	banner.style.width = '0px';
	
	draw_slide(false);

}

/*******************************************/
// HELPERS
/*******************************************/

function format_contact_info() {

	var contact_information;

	//all contact information is not guaranteed to exist..
	seller_name = document.getElementById('person_name').value;
	seller_company = document.getElementById('person_company').value;
	seller_email = document.getElementById('person_email').value;
	seller_phone_1 = document.getElementById('person_phone_1').value;
	seller_phone_2 = document.getElementById('person_phone_2').value;
	seller_url = document.getElementById('person_url').value;

	if (seller_name != null) {
	
		contact_information = seller_company + "<br />";
		contact_information = contact_information + seller_name;
			
		if (seller_email != '') {
			contact_information = contact_information + "<br /><a href='mailto:" + seller_email + "'>" + seller_email + "</a>";		
		}
		
		if (seller_phone_1 != '') {
			contact_information = contact_information + "<br />Phone: " + seller_phone_1;
		}
		if (seller_phone_2 != '') {
			contact_information = contact_information + "<br />Phone: " + seller_phone_2;
		}
	
		if (seller_url != '') {
			contact_information = contact_information + '<br /><br /><a href="' + seller_url + '" target="_blank">' + seller_url + '</a>';
		}	
	
	}
	
	var cd = document.getElementById('contact_data');
	cd.innerHTML = contact_information;
		
}

function format_description_info() {

	var description_data = document.getElementById('description_data');
	
	if (description_data != null) {
		
		//process links and emails in the description
		description_data.innerHTML = description_data.innerHTML.replace(/(([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+)/g, "<a href=\"mailto:$1\">$1</a>");
		description_data.innerHTML = description_data.innerHTML.replace(/(http:\/\/[^<\s\]]*)/g, "<a href=\"$1\" target=\"_blank\">$1</a>");

		var temp_html = '';
		if ((square_footage != null) && (square_footage.value != '')) {
			temp_html += 'Square Feet: ' + square_footage.value;
		}
		if ((price != null) && (price.value != '')) {
			temp_html += '<br />Price: ' + price.value;
		}
		if ((bedrooms != null) && (bedrooms.value != '')) {
			temp_html += '<br />Bedrooms: ' + bedrooms.value;
		}
		if ((bathrooms != null) && (bathrooms.value != '')) {
			temp_html += '<br />Bathrooms: ' + bathrooms.value;
		}
		
		if ((lot_size != null) && (lot_size.value != '')) {
			temp_html += '<br />Lot Size: ' + lot_size.value;
		}

		temp_html += '<br />';
		
		//realtor's requested that the bedrooms, price, appear on the top.
		//splice it into the top of the innerHTML
		description_data.innerHTML = temp_html + description_data.innerHTML;
	}	

}


//play the music if any was specified
function handle_audio() {

    //uses SWFObject to embed the XSPF MP3 player
	if ((listing_audio.value != null) && (listing_audio.value != '')) {
		var so = new SWFObject("/vtsuite/v6/audio/player_code/xspf_player_slim.swf?player_title=Music&autoplay=true&autoload=true&repeat_playlist=true&song_title=|&song_url=/vtsuite/v6/audio/" + listing_audio.value, "audioplayer", "85", "15", "6", "");
		so.write("audio_div");
	}

}

function fatal_error() {
	alert('Your browser does not seem to be compatible with this slideshow.');
}

/*******************************************/
// ATTACH DOM EVENTS NOW
/*******************************************/

window.onload = handle_onload;
window.onresize = handle_resize;