
//Global Vars
var screen_scrape_panel; //The main panel to hold results
var loading_panel; 		//Temp panel to display loading graphic
var success_panel;

//Global index tracking variables (hold current selection of each result type)
var current_desc;
var current_image;
var current_title;
var current_price;

//Glogal choice array variables (holds the arrays of each result types)
var desc_array;
var image_array;
var title_array;
var price_array;

//Global error variables
var scrape_alert_needed;
var scrape_alert_msg;

//--------------------------------------------------------------------------------------------
/*
*	display_panel
*		When the user enters a url and clicks get product info, make and AJAX request with the encoded URL
*		and display the loading panel while waiting for a response
*
*/
function display_panel(params) {
	
	if(params != null) {
		
		//Set the url based on the input url
		var url = params.url;
		var post_process = params.process_function;
	}
	else {
		
		//Default - get from product_url field
		var url = escape(document.getElementById("product_url").value);
		var post_process = null;
	}
	
	if(url == '') {
		
		alert("Please enter a URL to get Product Information!");
		return;
	}
	
	//Set up the post data and path
	var post_data = "action=main_display&product_url=" + url;
	var path = '/resources/ajax/_screen_scrape.one';

	// Initialize the temporary Panel to display while waiting for external content to load
	loading_panel = 
			new YAHOO.widget.Panel("wait",  
				{ width:"240px", 
				  fixedcenter:true, 
				  close:false, 
				  draggable:false, 
				  zIndex: 500,
				  modal:true,
				  visible:false
				} 
			);
	
	//Show the loading panel to the user
	loading_panel.setHeader("Fetching product information, please wait...");
	loading_panel.setBody('<img src="http://us.i1.yimg.com/us.yimg.com/i/us/per/gr/gp/rel_interstitial_loading.gif" />');
	loading_panel.render(document.body);
	loading_panel.show();

	//Make the AJAX request
	var request = YAHOO.util.Connect.asyncRequest('POST', path, {success: display_panel_ok, failure:ss_ajax_fail, argument:post_process}, post_data);	
	
}

//--------------------------------------------------------------------------------------------
/*
*	display_panel_ok
*		If the AJAX response is OK, then hide the loading panel, create the screen_scrape panel,
*		and hide the divs that hold the product details selections
*
*	@param o		The AJAX response object
*/
function display_panel_ok(o) {

	//Hide the loading panel
	loading_panel.hide();
	loading_panel = null;
	
	//Check for extra arguments passed in
	if (o.argument == null) {
		
		var post_process = create_scraper_entry;		
	}
	else {
		
		var post_process = o.argument;
	}
	

	//Get the current window width
	var myWidth = 0;
	
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}

	//Get the current scroll level
	var scrOfY = 0;
	
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}

	//Set the vars to center horizontally and set 50px down from current scroll location
	var left_pos = (myWidth-500) / 2;
	var top_pos = scrOfY;
	
	//JSON decode the result from the AJAX call
	var global_array = eval('(' + o.responseText + ')');
	
	if(global_array['error'] != null) {
		
		//Initialize the panel
		if (success_panel == null) {

			success_panel = new YAHOO.widget.SimpleDialog("success_panel", { 
					width : "300px",
					visible : false,
					draggable : false,
					fixedcenter : true,
					zIndex: 500,
					modal : true,
					close : true,
					buttons : [ { text:"OK", handler:hide_success_panel, isDefault:true }
							  ]					
				}
			);		
		}	

		//Alert the user that the product has been created 
		success_panel.setHeader("Your Product Has Been Created");
		success_panel.setBody("<br /><center><b>Sorry about that - there was an error retrieving your product!<br>Please try to enter the product URL again.</b></center>");

		success_panel.render(document.body);
		success_panel.show(); //Show the dialog box			
	}
	
	
	else {
		
		//Initialize the panel
		if (screen_scrape_panel == null) {

			screen_scrape_panel = new YAHOO.widget.SimpleDialog("screen_scrape_panel", { 
					width : "500px",
					x: left_pos,
					y: top_pos + 50,
					visible : false,
					draggable : true,
					zIndex: 500,
					modal : true,
					close : true,
					buttons : [ { text:"OK", handler:post_process, isDefault:true },
									{ text:"Close", handler:handle_close_scrape, isDefault:false } ]					
				}
			);		
		}		
		
		//Set up the global arrays
		image_array = global_array['result_array']['img'];
		desc_array = global_array['result_array']['desc'];
		title_array = global_array['result_array']['title'];
		price_array = global_array['result_array']['price'];

		//Set the current index to 0 for each array
		current_image = 0;
		current_title = 0;
		current_desc = 0;	
		current_price = 0;

		//Build the panel
		screen_scrape_panel.setHeader("Post Preview - Build Your Post");
		screen_scrape_panel.setBody(unescape(global_array['display']));

		screen_scrape_panel.render(document.body);
		screen_scrape_panel.show(); //Show the dialog box	

		if(unescape(global_array['display']) != 'There was an error processing your request.') {

			//Hide the div holding all the result choices
			document.getElementById("scrape_fix_results").style.display = "none";		
		}

	}

/*
	//For Debugging - just print out the JSON service call result
	screen_scrape_panel.setHeader("Post Preview - Build Your Post");
	screen_scrape_panel.setBody(o.responseText);
	
	screen_scrape_panel.render(document.body);
	screen_scrape_panel.show(); //Show the dialog box		
*/	
	
}

//--------------------------------------------------------------------------------------------
/*
*	display_choices
*		When the user clicks the fix results button, display all of the hidden select 
*		divs with selection choices
*/
function display_choices() {
	
	//Show the div holding all the result choices
	document.getElementById("scrape_fix_results").style.display = "inline";
}


//--------------------------------------------------------------------------------------------
/*
*	create_scraper_entry
*		When a user submits the form, make an AJAX request to create the HTML needed to convert
*		the preview panel into a blog post
*/
function create_scraper_entry() {
	
	//Get the form data
	var post_data = 'description=' + escape(desc_array[current_desc]) + '&title=' + title_array[current_title];
	post_data += '&image=' + image_array[current_image] + '&product_url_display=' + escape(document.getElementById("product_url_display").href);
	post_data += '&price=' + price_array[current_price];

	//Add the action to the post string
	post_data += "&action=submit_scraper_entry";
	var path = '/resources/ajax/_screen_scrape.one';
	
	//Make the AJAX request
	var request = YAHOO.util.Connect.asyncRequest('POST', path, {success: create_scraper_ok,failure:ss_ajax_fail}, post_data);	
}	


//--------------------------------------------------------------------------------------------
/*
*	create_scraper_ok
*		On a successful AJAX request, set the tinyMCE editor widnow to the response text, hide the creation
*		panel, and make sure that the all the divs from the creation panel are destroyed
*
*	@param o		The AJAX response object
*/
function create_scraper_ok(o) {
	
	
	//Set the hidden value that will store the value of the blog post created from the preview
	document.getElementById("submitted_product_info").value = o.responseText;
	
	//hide the main panel
	screen_scrape_panel.hide()
	screen_scrape_panel = null;
	
	//Create a title if one doesn't exist
	if(document.getElementById("post_title").value == '') {
		
		document.getElementById("post_title").value = title_array[current_title];
	}
	
	//Clean up the main panel's inner contents
	document.getElementById("scrape_results").innerHTML = '';
	
	//Initialize the panel
	if (success_panel == null) {

		success_panel = new YAHOO.widget.SimpleDialog("success_panel", { 
				width : "300px",
				visible : false,
				draggable : false,
				fixedcenter : true,
				modal : true,
				zIndex: 500,
				close : true,
				buttons : [ { text:"OK", handler:hide_success_panel, isDefault:true }
						  ]					
			}
		);		
	}	
	
	//Alert the user that the product has been created 
	success_panel.setHeader("Your Product Has Been Created");
	success_panel.setBody("<br /><center><b>Your product preview has been generated.<br>Please feel free to blog about the product below.</b></center>");
	
	success_panel.render(document.body);
	success_panel.show(); //Show the dialog box	
	
	document.getElementById("add_post_product_preview").style.display = "inline";
	
	var all_cats = document.blog_post_form.category.options;
	var i=0;
	var selected_index = document.blog_post_form.category.selectedIndex;
	
	//Initialize scrape alert variables
	scrape_alert_needed = false;
	scrape_alert_msg = "";
	
	//loop through all the categories
	for(i;i<all_cats.length;i++) {

		if (all_cats[i].text == 'Other') {

			//Remove the option
			document.blog_post_form.category.options[i] = null;

			if(selected_index == i) {
				
				//Set message and the fact that alert is needed
				scrape_alert_needed = true;
				scrape_alert_msg = "Please select another category for your post!";
				document.blog_post_form.category.selectedIndex = 0;
				break;
			}
			
		}
	}	
	
}


//========================== PANEL DIV CHANGING FUNCTIONS ===================================================
/**
*	change_preview_value
*		When a user selects a different option choice, update the display in the preview and then update the
*		new current index
*
*	@param change_type		The type of value to change
*	@param new_index		The new index of the item to display
*/
function change_preview_value(change_type,new_index) {
	
	//Change the preview and index based on the type
	switch(change_type) {
		//Update the price
		case 'price':
			//Set the price span value to the new price
			document.getElementById("price_span").innerHTML = price_array[new_index];
			current_price = new_index;		
			break;
		//Update the photo
		case 'photo':
			//Set the new image src to the new image	
			document.getElementById("preview_image").src = image_array[new_index];
			current_image = new_index;
			break;
		//Update the title
		case 'title':
			//Set the title span value to the new title
			document.getElementById("title_span").innerHTML = title_array[new_index];
			current_title = new_index;		
			break;		
		//Update the description
		case 'desc':
			//Set the description span to the new description
			document.getElementById("desc_span").innerHTML = unescape(desc_array[new_index]);
			current_desc = new_index;
			break;
		//Not a valid type, do nothing
		default:
			break;
		
	}
	
}

//---------------------------------------------------------------------------------------------------------
/**
*	user_submit_value
*		When a user enters a custom value for a given field, then set the appropriate span text for
*		based on the user input
*
*	@param user_type		The type of user value submitted
*/
function user_submit_value(user_type) {
	
	//Initialize the holder variables
	var user_value;
	var new_index;
	
	//Set the variables based on the user types
	switch(user_type) {
		//Set up the price array/variable
		case 'price':
			user_value = document.getElementById("user_price").value;
			new_index = price_array.length;
			price_array[new_index] = user_value;
			current_price = new_index;
			//Set the price span text
			document.getElementById("price_span").innerHTML = user_value;
			break;
		//Set up the title array/variable	
		case 'title':
			user_value = document.getElementById("user_title").value;
			new_index = title_array.length;
			title_array[new_index] = user_value;
			current_title = new_index;
			//Set the title span text
			document.getElementById("title_span").innerHTML = user_value;
			break;	
		//Set up the description array/variable	
		case 'desc':
			user_value = document.getElementById("user_desc").value;
			new_index = desc_array.length;
			desc_array[new_index] = user_value;
			current_desc = new_index;
			//Set the description span text
			document.getElementById("desc_span").innerHTML = user_value;
			break;				
		//Set up the description array/variable	
		case 'image':
			user_value = document.getElementById("user_image").value;
			new_index = image_array.length;
			image_array[new_index] = user_value;
			current_image = new_index;
			//Set the image span 
			document.getElementById("preview_image").src = user_value;
			break;				
		default:
			//Do nothing
			break;		
	}
}



function generate_product_preview()
{  
	var prod_preview = document.getElementById("submitted_product_info").value;
	
	//Initialize the panel
	if (success_panel == null) {

		success_panel = new YAHOO.widget.SimpleDialog("success_panel", { 
				width : "350px",
				visible : false,
				draggable : false,
				fixedcenter : true,
				zIndex: 500,
				modal : true,
				close : true,
				buttons : [ { text:"OK", handler:hide_success_panel, isDefault:true }
						  ]					
			}
		);		
	}	
	
	//Alert the user that the product has been created 
	success_panel.setHeader("Here is your product preview:");
	success_panel.setBody(unescape(prod_preview));
	
	success_panel.render(document.body);
	success_panel.show(); //Show the dialog box		

}


//========================== GENERIC HANDLER FUNCTIONS ===================================================
/*
*	Alert the failed AJAX submission
*/
function ss_ajax_fail(o) {

	if(loading_panel != null) {
		//Hide the loading panel
		loading_panel.hide();
		loading_panel = null;
	}

	
	if(screen_scrape_panel != null) {
		//Hide the loading panel
		screen_scrape_panel.hide();
		screen_scrape_panel = null;
	}	
	
	
	//Check for additional alerts to user
	if(scrape_alert_needed) {
		
		alert(scrape_alert_msg);
		scrape_alert_msg = "";
		scrape_alert_needed = false;
	}	

}	

/*
*	Hide the scraper panel when it is closed
*/
function handle_close_scrape() {

	screen_scrape_panel.hide();
	screen_scrape_panel = null;

	//Check for additional alerts to user
	if(scrape_alert_needed) {
		
		alert(scrape_alert_msg);
		scrape_alert_msg = "";
		scrape_alert_needed = false;
	}	

}	


/*
*	Hide the success panel when it is closed
*/
function hide_success_panel() {

	success_panel.hide();
	success_panel = null;
	
	//Check for additional alerts to user
	if(scrape_alert_needed) {
		
		alert(scrape_alert_msg);
		scrape_alert_msg = "";
		scrape_alert_needed = false;
	}
}	








