var item_hashed = false;

var items_to_local_parse = 10;
var items_parsed = 0; 
var global_article_id = "";
var allow_fb_popup = true;
var login_box_content = '';

//Uservoice Feedback:
if (screen.width>=1200) {
		var uvOptions = {};
(function() {
    var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
    uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/7UIN89d6ulOjPYkYMBW7ew.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
})();}
//End of Uservoice widget

function set_share_button_single(obj) {
}

var share_box_opened = false;
function open_share_box(node_id) {
	if (!share_box_opened) {
		jQuery.ajax({
			url: '/drippler_ajax/share_box/'+node_id,		
			success: function(data) {				
				jQuery.colorbox({
					onClosed:function(){ share_box_opened = false; },
					html: data, innerWidth:450, innerHeight:100, initialWidth: 450, initialHeight: 100, scrolling: false, opacity: 0});				
				share_box_opened = true;
									
				FB.Event.subscribe('edge.create', function(response) {
					jQuery.fn.colorbox.resize({innerWidth:450, innerHeight:240});
				});
				FB.Event.subscribe('edge.remove', function(response) {
					jQuery.fn.colorbox.resize({innerWidth:450, innerHeight:100});
				});
			}
		});		
	}
}


jQuery(document).ready(function($) {
	//autopager:
	if(jQuery.isFunction(Drupal.flagAnonymousLinks)) Drupal.flagAnonymousLinks();
	if (Drupal.settings.views_infinite_scroll == null && $.autopager!=null) {
		var img = '<div id="views_infinite_scroll-ajax-loader" style="text-align: center; clear:both; float:none;"><img src="/sites/all/modules/views_infinite_scroll/images/ajax-loader.gif" alt="loading..."/></div>';
		$.autopager({
			appendTo: '.drips-panel ul.drips',
			content: '.drips-row',
			start: function() {
				$('.drips-panel ul.drips').after(img);
			},
			load: function() {    
				$('div#views_infinite_scroll-ajax-loader').remove();
				drippler_set_read_more_links();         
				Drupal.attachBehaviors();
				drippler_set_analytics_events();
				Drupal.flagAnonymousLinks();
			},
			page: 0
		});
	}
	jQuery.expr[':'].regex = function(elem, index, match) {
	    var matchParams = match[3].split(','),
	        validLabels = /^(data|css):/,
	        attr = {
	            method: matchParams[0].match(validLabels) ? 
	                        matchParams[0].split(':')[0] : 'attr',
	            property: matchParams.shift().replace(validLabels,'')
	        },
	        regexFlags = 'ig',
	        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
	    return regex.test(jQuery(elem)[attr.method](attr.property));
	}
	//Exmaple text for input fields
	if (jQuery('form#search-block-form input.form-text').val() != 'undefined')
		jQuery('form#search-block-form input.form-text').example('Search gadgets');
	if (jQuery('#drippler_wizard_search').val() != 'undefined')
		jQuery('#drippler_wizard_search').example('Search gadgets');
	
	//flags behivor!
	$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
		if (Drupal.settings.currentUser == 0) {
			SetCookie('no_cache' , '1', 1);
		}
		if (data.flagStatus == 'flagged' && data.flagName == 'like') {
			//open colorbox!!! :)))
			open_share_box(data.contentId);
			//get the count and add one			
			//var nodeid = my_element.find("a").attr('href').replace(/.*#([0-9]+)\-.*$/m, '$1');			
			var view_count = $("span:contains('"+data.contentId+"')").parent().parent().find('.like-count').text();
			//var insert_view_obj = $("span:contains('"+data.contentId+"')").parent().parent().find('.like-count');
			var insert_view_obj = $(".like-count-"+data.contentId);	
			if (view_count == '') {
				var view_count = $('span[class="flag-wrapper flag-like flag-like-'+data.contentId+'"]').parent().parent().parent().parent().parent().find('span.field-content.like-count').text();
				var insert_view_obj = $('span[class="flag-wrapper flag-like flag-like-'+data.contentId+'"]').parent().parent().parent().parent().parent().find('span.field-content.like-count');
			}					
			view_count = parseInt(view_count)+1;
			insert_view_obj.html(view_count);			
		} else if (data.flagStatus == 'unflagged' && data.flagName == 'like') {
			var view_count = $("span:contains('"+data.contentId+"')").parent().parent().find('.like-count').text();
			//var insert_view_obj = $("span:contains('"+data.contentId+"')").parent().parent().find('.like-count');
			var insert_view_obj = $(".like-count-"+data.contentId);
			if (view_count == '') {
				var view_count = $('span[class="flag-wrapper flag-like flag-like-'+data.contentId+'"]').parent().parent().parent().parent().parent().find('span.field-content.like-count').text();
				var insert_view_obj = $('span[class="flag-wrapper flag-like flag-like-'+data.contentId+'"]').parent().parent().parent().parent().parent().find('span.field-content.like-count');
			}						
			if (view_count >= 1) {
				view_count = view_count-1;
			}
			insert_view_obj.html(view_count);
		}
		Drupal.flagAnonymousLinks();
	});
	drippler_set_read_more_links();
	drippler_set_have_want_buttons();
	drippler_attach_remove_buttons();
	jQuery(window).hashchange( function(){
	    // Alerts every time the hash changes!
		if (item_hashed == true) {
		    if (location.hash == '') {
		    	window.location.reload();
		    } else {
		    	var parts = location.hash.split("#!");
		    	if (parts[1]==null) {
		    		parts = location.hash.split("#");
		    	}
		    	if (parts[1]) {
		    		var parts = parts[1].split("-");	
		    		var node_id = parts[0];	
		    	}
		    	if (!single_loaded) drippler_articles_get_article(node_id);
		    	  else single_loaded = false;
		    	//drippler_articles_get_article(nodeid);
		    }
		}
	  });
	  // Trigger the event (useful on page load).	  
	jQuery(window).hashchange();
	///SET AJAX LISTENERS WHEN AJAX COMMAND IS DONE (for next/previous buttons).
	jQuery(".active").ajaxSuccess( function(){
		drippler_set_read_more_links();			
	});
	jQuery("#category").ajaxSuccess( function(){
		if (click_origin != 'buttons') {
			drippler_set_have_want_buttons();
			click_origin = '';
		}
	});
	jQuery("#brand").ajaxSuccess( function(){
		if (click_origin != 'buttons') {
			drippler_set_have_want_buttons();
			click_origin = '';
		}
	});
});

var click_origin = '';

function drippler_set_have_want_buttons() {		
	jQuery(".drippler_have_button").each(function(index) {
		drippler_have_want_buttons('have', jQuery(this));
	});	
	jQuery(".drippler_want_button").each(function(index) {
		drippler_have_want_buttons('want', jQuery(this));
	});		
}

function drippler_build_table_structure(drippler_box) {
	resetBoxParam = false;
	//Check if boxes structure exists
	if (jQuery(drippler_box).find('.field-content').html() == null) {
		//need to create field-content
		var field_content_span = document.createElement('span');
		field_content_span = jQuery(field_content_span).attr('class','field-content');
		drippler_box.append(field_content_span);
		resetBoxParam = true;
	}
	if (jQuery(drippler_box).find('.field-content').find('.item-list').html() == null) {
		//need to create div item list
		var field_content_div = document.createElement('div');
		field_content_div = jQuery(field_content_div).attr('class','item-list');
		jQuery(drippler_box).find('.field-content').append(field_content_div);
		resetBoxParam = true;
	}					
	if (jQuery(drippler_box).find('.field-content').find('.item-list').find('ul').html() == null) {
		//need to create div item list
		var field_content_ul = document.createElement('ul');
		var field_content_li = document.createElement('li');
		//jQuery(field_content_ul).append(field_content_li);
		jQuery(drippler_box).find('.field-content').find('.item-list').append(field_content_ul);
		resetBoxParam = true;
	}	
	return resetBoxParam;
}

function strpos_j(haystack, needle, offset) {
	  var i = (haystack+'').indexOf(needle, (offset || 0));
	  return i === -1 ? false : i;
}

function extract_node_id(class_name) {
	var myRegex = /button_node_id_(\d+)/;
	match = myRegex.exec(class_name);
	var push_id = 0;
	if (match != null) {
		push_id = match[1];
	}
	return push_id;
}


function drippler_have_want_buttons(request, object) {
	//We need to create an empty div and fill it with the data and make it a dialog
	var newDiv = document.createElement('div');
	//hidding it
	jQuery(newDiv).css('display','none');
	jQuery('body').append(newDiv);
	var notclean_id = jQuery(object).attr('class');
	var myRegex = /button_node_id_(\d+)/;
	match = myRegex.exec(notclean_id);
	var push_id = 0;
	if (match != null) {
		push_id = match[1];
	}			
	if (push_id != 0) {
				
		jQuery(this).unbind('click');
		jQuery(object).click(function(event) {			
			//Need to check if user is not logged in just show colorbox!!!
			if (Drupal.settings.currentUser == 0) {
				click_origin = 'buttons';
				if (request == 'have') {
					if (ReadCookie('drippler_products_want') == push_id) {
						SetCookie('drippler_products_want' , '', 5);
					}
					SetCookie('drippler_products_have' , push_id, 5);					
				} else {
					if (ReadCookie('drippler_products_have') == push_id) {
						SetCookie('drippler_products_have' , '', 5);
					}
					SetCookie('drippler_products_want' , push_id, 5);					
				}							
				//jQuery('#product_name').append(newA);
				Drupal.settings.fb.reload_url = "/user/gadgets"; //redirect to wizard after registration
				open_register_box(request, push_id);
			} else {
			jQuery.ajax({
				url: Drupal.settings.basePath+"drippler_ajax/products/"+((request=="have")?"have":"want")+"/"+push_id,					
				dataType: "json",
				type: 'POST',
				data: 'id='+push_id,
				async: false,
				success: function(data, textStatus, jqXHR){	
					var node_real_title = data.product_name;
					click_origin = 'buttons';
					//remove Wizard marks
					removeWizardMark(push_id);					
					//Need to check if the Want Have Table exists add to the right place
					var drippler_want_box = jQuery('div.views-field-field-want');						
					var drippler_want_box_ul = drippler_want_box.find('ul');
					var drippler_want_box_li = drippler_want_box_ul.find('li');
					
					var drippler_have_box = jQuery('div.views-field-field-have');						
					var drippler_have_box_ul = drippler_have_box.find('ul');
					var drippler_have_box_li = drippler_have_box_ul.find('li');
					
					var resetBoxParam = drippler_build_table_structure(drippler_want_box);
					if (resetBoxParam) {
						var drippler_want_box = jQuery('div.views-field-field-want');						
						var drippler_want_box_ul = drippler_want_box.find('ul');
						var drippler_want_box_li = drippler_want_box_ul.find('li');
					}
					var resetBoxParam = drippler_build_table_structure(drippler_have_box);
					if (resetBoxParam) {
						var drippler_have_box = jQuery('div.views-field-field-have');						
						var drippler_have_box_ul = drippler_have_box.find('ul');
						var drippler_have_box_li = drippler_have_box_ul.find('li');
					}
										
					if (request == 'want') {						
						var node_title = jQuery.trim(jQuery(object).parent().parent().parent().parent().find('.views-field-title').text());
						if (node_title == '') {
							node_title = jQuery.trim(jQuery(object).prev().text());
						}	
						var user_wants = new Array();					
						var removed = false;						
						jQuery(drippler_want_box_li).each(function() {
							extracted_id = extract_node_id(jQuery(this).find('div').attr('class'));							
							//if (jQuery(this).text() == node_title) {
							if (push_id == extracted_id) {
								//Allready inside need to remove
								jQuery(this).remove();		
								jQuery(object).removeClass('active');
								removed = true;
							}							
							//user_wants.push(jQuery(this).text());
						});
						if (!removed) {							
							var drippler_new_li = document.createElement('li');
							var drippler_new_a = document.createElement('span');
							//jQuery(drippler_new_a).attr('href','#');
							//jQuery(drippler_new_a).text(node_title);
							jQuery(drippler_new_a).text(node_real_title);														
							
							var drippler_new_remove_button = document.createElement('div');
							var drippler_class_name = 'drippler_want_remove_button button_node_id_'+push_id;
							var drippler_button_id = 'button_node_id_'+push_id;
							jQuery(drippler_new_remove_button).attr('class',drippler_class_name);
							//jQuery(drippler_new_remove_button).html('<img src="http://penguinlovesmusic.de/wp-content/uploads/remove.pn">');
							
							jQuery(drippler_new_li).append(drippler_new_remove_button);
							
							jQuery(drippler_new_li).append(drippler_new_a);
							
							jQuery(drippler_want_box_ul).append(drippler_new_li);
																																		
									
							var find_class_name = jQuery(object).attr('class');
							find_class_name = find_class_name.replace(/ /g,".");							
							//want-it drippler_want_button button_node_id_21520 trackevent event_Wizard_Want_21520
							if (data.action == 'add') {
								jQuery("."+find_class_name).addClass('active');
							    if (allow_fb_popup && !('ontouchstart' in window)) {
									FB.getLoginStatus(function(response) {
										  if (response.status!='unknown') {
										    // user logged in to facebook
											  var obj = {
													  //show_error: true,
													  method: 'feed',
													  link: 'http://drippler.com?utm_medium=Facebook&utm_source=Wall_post&utm_campaign=v2',
													  picture: data.picture,
													  name: "I just added the "+data.product_full_name+" to my gadgets on Drippler!",
													  //caption: "Drippler is cool free service that keeps me updated on my gadgets!",
													  description: "Drippler keeps me up to date with everything I need to know about my gadgets: news, rumors, tips, firmware updates, apps, tech-support, manuals & more. Check it out!",
													  actions: [{name: 'Check it out!', link:'http://drippler.com?utm_medium=Facebook&utm_source=Wall_post&utm_campaign=v2'}],
													  display: 'popup'
											  };
											  _gaq.push(['_trackEvent','Invitations', 'Gadget Add Popup', 'Popup']);
											  FB.ui(obj, function(response){fb_wall_product_add_callback(response, 'Want')});
										  }
										});
							    }
							}
							if (data.action == 'remove') {
								jQuery("."+find_class_name).removeClass('active');
							}
							jQuery("."+find_class_name).prev().removeClass('active');
							jQuery(drippler_have_box_li).each(function() {
								extracted_id = extract_node_id(jQuery(this).find('div').attr('class'));
								if (extracted_id == push_id) {
									//Allready inside need to remove
									jQuery(this).remove();												
								}							
							});							
						}
					} else {
						//request is 'have'																	
						var node_title = jQuery.trim(jQuery(object).parent().parent().parent().parent().find('.views-field-title').text());
						if (node_title == '') {
							node_title = jQuery.trim(jQuery(object).prev().text());
						}						
						var user_haves = new Array();					
						var removed = false;
						jQuery(drippler_have_box_li).each(function() {
							extracted_id = extract_node_id(jQuery(this).find('div').attr('class'));							
							//if (jQuery(this).text() == node_title) {
							if (push_id == extracted_id) {
								//Allready inside need to remove
								jQuery(this).remove();		
								jQuery(object).removeClass('active');
								removed = true;
							}				
							//user_haves.push(jQuery(this).text());
						});
						//Remove from the second box also						
						if (!removed) {
							var drippler_new_li = document.createElement('li');
							var drippler_new_a = document.createElement('span');
							//jQuery(drippler_new_a).attr('href','#');
							//jQuery(drippler_new_a).text(node_title);
							jQuery(drippler_new_a).text(node_real_title);							
							
							var drippler_new_remove_button = document.createElement('div');
							var drippler_class_name = 'drippler_have_remove_button button_node_id_'+push_id;
							var drippler_button_id = 'button_node_id_'+push_id;
							jQuery(drippler_new_remove_button).attr('class',drippler_class_name);
							//jQuery(drippler_new_remove_button).html('<img src="http://penguinlovesmusic.de/wp-content/uploads/remove.png">');
							
							jQuery(drippler_new_li).append(drippler_new_remove_button);
							
							jQuery(drippler_new_li).append(drippler_new_a);
							
							jQuery(drippler_have_box_ul).append(drippler_new_li);
							
							var find_class_name = jQuery(object).attr('class');
							find_class_name = find_class_name.replace(/ /g,".");
							
							if (data.action == 'add') {
								jQuery("."+find_class_name).addClass('active');
								jQuery("."+find_class_name).addClass('active');
							    if (allow_fb_popup && !('ontouchstart' in window)) {
									FB.getLoginStatus(function(response) {
										  if (response.status!='unknown') {
										    // user logged in to facebook
											  var obj = {
													  //show_error: true,
													  method: 'feed',
													  link: 'http://drippler.com?utm_medium=Facebook&utm_source=Wall_post&utm_campaign=v2',
													  picture: data.picture,
													  name: "I just added the "+data.product_full_name+" to my gadgets on Drippler!",
													  //caption: "Drippler is cool free service that keeps me updated on my gadgets!",
													  description: "Drippler keeps me up to date with everything I need to know about my gadgets: news, rumors, tips, firmware updates, apps, tech-support, manuals & more. Check it out!",
													  actions: [{name: 'Check it out!', link:'http://drippler.com?utm_medium=Facebook&utm_source=Wall_post&utm_campaign=v2'}],
													  display: 'popup'
											  };
											  _gaq.push(['_trackEvent','Invitations', 'Gadget Add Popup', 'Popup']);
											  FB.ui(obj, function(response){fb_wall_product_add_callback(response, 'Have')});
										  }
										});
							    }
							}
							if (data.action == 'remove') {
								//jQuery(object).removeClass('active');
								jQuery("."+find_class_name).removeClass('active');
							}
							jQuery("."+find_class_name).next().removeClass('active');
							//Remove from other box
							jQuery(drippler_want_box_li).each(function() {
								extracted_id = extract_node_id(jQuery(this).find('div').attr('class'));
								if (extracted_id == push_id) {
								//if (jQuery(this).text() == node_title) {
									//Allready inside need to remove
									jQuery(this).remove();											
								}							
								//user_wants.push(jQuery(this).text());
							});
							
						}
					}
					drippler_attach_remove_buttons();
				}
			});
			}
		});
	}
}

function drippler_attach_single_remove_button(classname, request) {	
	drippler_have_want_buttons(request, jQuery.find('.'+classname));
}
function drippler_attach_remove_buttons() {	
	jQuery('.drippler_have_remove_button').each(function() {
		jQuery(this).unbind();
		drippler_have_want_buttons('have', jQuery(this));
	});
	jQuery('.drippler_want_remove_button').each(function() {
		jQuery(this).unbind();
		drippler_have_want_buttons('want', jQuery(this));
	});
}

function drippler_set_ajax_event_listener() {
	return; //do we still need this function??
	items_parsed = 0;
	jQuery(".views-row").each(function(index) {
			var my_row = jQuery(this);		
		//my_row.find(".drippler_ajax_link").each(function(index) {
			if (custom_drip_page) {
				items_to_local_parse = 100;
			}
	  		var my_element = jQuery(this);   		
	    	var place_holder = my_row;  		
	  		var article_id = parseInt(place_holder.find(".drippler_node_id").text());
	  		if (!isNaN(article_id)) {
	  			var node_title = place_holder.find("a").text();
		  		if (items_parsed < items_to_local_parse) {	    	
		  			global_article_id = article_id;
		  			var text_place_holder = place_holder.find(".text_holder");
		  			if (text_place_holder.length == 0) {
			  			place_holder.append("<div class=\'text_holder\'></div>");
		  				var text_place_holder = place_holder.find(".text_holder");
		  			}
		  			jQuery(this).unbind('click');
		  			if (typeof Articles != 'undefined') {
			  			jQuery(this).click(function() {	  				
			    			var my_element = jQuery(this);   			    			
			    			var place_holder = my_row;
			  				var article_id = parseInt(place_holder.find(".drippler_node_id").text());
			  				if (text_place_holder.text() == "") {
			    				place_holder.find(".drippler_ajax_content").html(Articles[article_id]);
			    			} else {   
			    				//text_place_holder.html("");
			    			}
			    		});
			  			jQuery(this).click();
		  			}
		    	} else {	    
		    		jQuery(this).find(".drippler_ajax_link").unbind('click');
		    		jQuery(this).find(".drippler_ajax_link").click(function() {	    			
		    			jQuery.ajax({
		    				url: Drupal.settings.basePath+"drippler_ajax/get_article_summary/"+article_id,
		    				dataType: "html",
		    				success: function(data, textStatus, jqXHR){
		              		place_holder.find(".drippler_ajax_content").html(data); 		
		    				}
		  				});
		    		});
		    	}
		    	items_parsed = items_parsed + 1;
	  		}
	});	
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};
function make_nice_url(url) {
	//url.replace(' ','-');
	url = jQuery.trim(url);
	var cleanUrl = (url + " ").replace(/[^a-zA-Z0-9]+/g, "-");
	if (cleanUrl[0] == '-') {
		cleanUrl = cleanUrl.slice(1, cleanUrl.length -1);
	} else {
		cleanUrl = cleanUrl.slice(0, cleanUrl.length -1);
	}
	return cleanUrl.toLowerCase();	
}
var run_once = false;
function drippler_set_read_more_links() {
	if (run_once == false) {
		jQuery(".read-more-button").each(function(e) {
			var my_element = jQuery(this);
					
			//e.preventDefault();	
			//var nodeid = jQuery(this).attr("href").substr(jQuery(this).attr("href").indexOf('#'),jQuery(this).attr("href").length).replace('#', '');			
			var nodeid = my_element.find("a").attr('href').replace(/.*#!?([0-9]+)\-?.*$/m, '$1');
			var href_node_title = my_element.find("a").attr('href').replace(/.*#!?[0-9]+\-?(.*)$/m, '$1');	
			var node_title = my_element.parent().find(".top-title").text();
			node_title = jQuery.trim(node_title);
			if (node_title == '') {
				node_title = my_element.parent().parent().find(".views-field-title").text();
				node_title = jQuery.trim(node_title);
				if (node_title == '') {
					node_title = my_element.parent().parent().parent().find(".views-field-title").text();
					node_title = jQuery.trim(node_title);
				} else
				if (node_title == '') {
					node_title = jQuery.trim(my_element.text());
				}
			}				
			var normal_title = node_title;
			//need to cut everything after pipe in title
			var pipe_index = node_title.indexOf('|');
			if (pipe_index !== -1) {			
				node_title = node_title.substr(0,pipe_index);
				normal_title = normal_title.substr(0,pipe_index);
			}
			node_title = make_nice_url(node_title);			//need to set event listener for the read_more link to open single page
			href_node_title = make_nice_url(href_node_title);
			if (nodeid != '' && node_title != '') {
				//jQuery(this).click(function(e) {
				my_element.find("a").unbind('click', drippler_read_more_handler);
				my_element.find("a").bind('click', {nodeid:nodeid,node_title:node_title,normal_title:normal_title},  drippler_read_more_handler);
			}
		});		
	}
}

function drippler_read_more_handler(event) {
	single_loaded = true;
	//Remove pager functionality if exists.
	if (jQuery.isFunction(jQuery.autopager))
		  jQuery.autopager('destroy');
	item_hashed = true;
	window.location.hash = '!'+event.data.nodeid;
	event.preventDefault();
	drippler_articles_get_article(event.data.nodeid);
	resetBreadcrumbs();
	var check_breads = jQuery('.breadcrumbs').text();
	check_breads += '&raquo; '+event.data.normal_title;					
	if (check_breads.length >= 114) {
		//need to substract the title..
		var substract = check_breads.length - 114;
		var sub_from_title = event.data.normal_title.length - substract;
		event.data.normal_title = normal_title.substr(0,sub_from_title);
		event.data.normal_title += '...';
	}
	jQuery('.breadcrumbs').append('<div itemscope itemtype="http://data-vocabulary.org/Breadcrumb"> &raquo; <a href="' + location.pathname + window.location.hash + '" itemprop="url"><span itemprop="title">'+event.data.normal_title+'</span></a></div>');
}

function drippler_articles_get_article(node_id) {
	if (typeof(node_id) != 'undefined') {
		var item = jQuery('input:hidden[name=cat_item_nid]').val();
		var ajaxUrl = Drupal.settings.basePath+"drippler_ajax/get_article/"+node_id;
		if (item>0) ajaxUrl = ajaxUrl+"/"+item;
		jQuery.ajax({
			  url: ajaxUrl,
			  context: document.body,
			  dataType: 'html',
			  beforeSend: function() {
				  jQuery('.view-related-products').remove();
                  jQuery('html').animate({scrollTop:0}, 200);
                  jQuery('body').animate({scrollTop:0}, 200);
                  jQuery('.article-replace').animate({'margin-top':'860px', duration:500}, 500).animate({opacity:0},500);
			  },
			  success: function(data, textStatus, jqXHR){
				  jQuery('.article-replace').remove();
				  if (jQuery.isFunction(jQuery.autopager))
					  jQuery.autopager('destroy');
				  jQuery('#related-drips').remove();
				  jQuery('.drips-panel .pane-content:first div:first').prepend(data);
				  jQuery('div.pane-category div.related-drips-more').remove();
				  jQuery('#brand div.related-drips-more').remove();
				  jQuery('.article-replace').css({'margin-top':'860px'});
				  jQuery('.article-replace').animate({'margin-top':'0px'}, 500);
		  		  jQuery('.content_pane').fadeIn(300);
				  Drupal.flagAnonymousLinks();
		  		  report_analytics('single-page');
		  		  drippler_set_analytics_events();
		  		  drippler_set_read_more_links();
		  		  Drupal.attachBehaviors(data);
		  		  FB.XFBML.parse(document);
			  }
		});
	}	
}

function mark_latest() {	
	jQuery('#drippler_upper_buttons div').removeClass('drip_active');
	jQuery('#drippler_latest_button').addClass('drip_active');
}
function mark_popular() {	
	jQuery('#drippler_upper_buttons div').removeClass('drip_active');
	jQuery('#drippler_popular_button').addClass('drip_active');
}
function mark_favorites() {	
	jQuery('#drippler_upper_buttons div').removeClass('drip_active');
	jQuery('#drippler_favorites_button').addClass('drip_active');
}
function removeWizardMark(node_id) {
	var jObj = jQuery.find('div.drippler_have_remove_button.button_node_id_'+node_id);	
	var clicked_item = jQuery(jObj).prev().text();	
	var wizObj = jQuery.find('#drippler_wizard_product_results');	
	jQuery(wizObj).find('td').each(function(index) {
		var mtd = jQuery(this);
		var running_item = jQuery.trim(mtd.find('.views-field-title').text());		
		var running_item = jQuery.trim(mtd.find('.views-field-php').find('span').find('span').attr('class'));
		running_item = extract_node_id(running_item);		
		if (node_id == running_item) {			
			jQuery('span.button_node_id_'+node_id).removeClass('active');			
		}
	});
	//Dotan New View need to run overit too.	
	var wizObj = jQuery.find('.view-id-wizard_product_results');	
	jQuery(wizObj).find('td').each(function(index) {
		var mtd = jQuery(this);
		var running_item = jQuery.trim(mtd.find('.views-field-title').text());		
		var running_item = jQuery.trim(mtd.find('.views-field-php').find('span').find('span').attr('class'));
		running_item = extract_node_id(running_item);		
		if (node_id == running_item) {			
			jQuery('span.button_node_id_'+node_id).removeClass('active');			
		}
	});	
	//views-field-title
}
function resetBreadcrumbs() {
	jQuery('#breadcrumb').find('.breadcrumbs').html(original_breadcrumbs);
}

function is_array(input){
  return typeof(input)=='object'&&(input instanceof Array);
}

(function ($) {
	$.resetSlideShow = function() {
	$('.views_slideshow_cycle_main:not(.viewsSlideshowCycle-processed)', document.body).addClass('viewsSlideshowCycle-processed').each(function() {

        var fullId = '#' + $(this).attr('id');
        var settings = Drupal.settings.viewsSlideshowCycle[fullId];
        settings.targetId = '#' + $(fullId + " :first").attr('id');
        settings.slideshowId = settings.targetId.replace('#views_slideshow_cycle_teaser_section_', '');
        settings.paused = false;

        settings.opts = {
          speed:settings.speed,
          timeout:settings.timeout,
          delay:settings.delay,
          sync:settings.sync,
          random:settings.random,
          nowrap:settings.nowrap,
          after:function(curr, next, opts) {
            // Need to do some special handling on first load.
            var slideNum = opts.currSlide;
            if (typeof settings.processedAfter == 'undefined' || !settings.processedAfter) {
              settings.processedAfter = 1;
              slideNum = (typeof settings.opts.startingSlide == 'undefined') ? 0 : settings.opts.startingSlide;
            }
            Drupal.viewsSlideshow.action({ "action": 'transitionEnd', "slideshowID": settings.slideshowId, "slideNum": slideNum });
          },
          before:function(curr, next, opts) {
            // Remember last slide.
            if (settings.remember_slide) {
              createCookie(settings.vss_id, opts.currSlide + 1, settings.remember_slide_days);
            }

            // Make variable height.
            if (!settings.fixed_height) {
              //get the height of the current slide
              var $ht = $(this).height();
              //set the container's height to that of the current slide
              $(this).parent().animate({height: $ht});
            }

            // Need to do some special handling on first load.
            var slideNum = opts.nextSlide;
            if (typeof settings.processedBefore == 'undefined' || !settings.processedBefore) {
              settings.processedBefore = 1;
              slideNum = (typeof settings.opts.startingSlide == 'undefined') ? 0 : settings.opts.startingSlide;
            }

            Drupal.viewsSlideshow.action({ "action": 'transitionBegin', "slideshowID": settings.slideshowId, "slideNum": slideNum });
          },
          cleartype:(settings.cleartype)? true : false,
          cleartypeNoBg:(settings.cleartypenobg)? true : false
        };

        // Set the starting slide if we are supposed to remember the slide
        if (settings.remember_slide) {
          var startSlide = readCookie(settings.vss_id);
          if (startSlide == null) {
            startSlide = 0;
          }
          settings.opts.startingSlide =  startSlide;
        }

        if (settings.effect == 'none') {
          settings.opts.speed = 1;
        }
        else {
          settings.opts.fx = settings.effect;
        }

        // Take starting item from fragment.
        var hash = location.hash;
        if (hash) {
          var hash = hash.replace('#', '');
          var aHash = hash.split(';');
          var aHashLen = aHash.length;

          // Loop through all the possible starting points.
          for (var i = 0; i < aHashLen; i++) {
            // Split the hash into two parts. One part is the slideshow id the
            // other is the slide number.
            var initialInfo = aHash[i].split(':');
            // The id in the hash should match our slideshow.
            // The slide number chosen shouldn't be larger than the number of
            // slides we have.
            if (settings.slideshowId == initialInfo[0] && settings.num_divs > initialInfo[1]) {
              settings.opts.startingSlide = parseInt(initialInfo[1]);
            }
          }
        }

        // Pause on hover.
        if (settings.pause) {
          $('#views_slideshow_cycle_teaser_section_' + settings.vss_id).hover(function() {
            Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": settings.slideshowId });
          }, function() {
            if (!settings.paused) {
              Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": settings.slideshowId });
            }
          });
        }

        // Pause on clicking of the slide.
        if (settings.pause_on_click) {
          $('#views_slideshow_cycle_teaser_section_' + settings.vss_id).click(function() {
            settings.paused = true;
            Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": settings.slideshowId });
          });
        }

        if (typeof JSON != 'undefined') {
          var advancedOptions = JSON.parse(settings.advanced_options);
          for (var option in advancedOptions) {
            advancedOptions[option] = $.trim(advancedOptions[option]);
            advancedOptions[option] = advancedOptions[option].replace(/\n/g, '');
            if (!isNaN(parseInt(advancedOptions[option]))) {
              advancedOptions[option] = parseInt(advancedOptions[option]);
            }
            else if (advancedOptions[option].toLowerCase() == 'true') {
              advancedOptions[option] = true;
            }
            else if (advancedOptions[option].toLowerCase() == 'false') {
              advancedOptions[option] = false;
            }

            switch(option) {

              // Standard Options
              case "activePagerClass":
              case "allowPagerClickBubble":
              case "autostop":
              case "autostopCount":
              case "backwards":
              case "bounce":
              case "cleartype":
              case "cleartypeNoBg":
              case "containerResize":
              case "continuous":
              case "delay":
              case "easeIn":
              case "easeOut":
              case "easing":
              case "fastOnEvent":
              case "fit":
              case "fx":
              case "height":
              case "manualTrump":
              case "next":
              case "nowrap":
              case "pager":
              case "pagerEvent":
              case "pause":
              case "pauseOnPagerHover":
              case "prev":
              case "prevNextEvent":
              case "random":
              case "randomizeEffects":
              case "requeueOnImageNotLoaded":
              case "requeueTimeout":
              case "rev":
              case "slideExpr":
              case "slideResize":
              case "speed":
              case "speedIn":
              case "speedOut":
              case "startingSlide":
              case "sync":
              case "timeout":
                settings.opts[option] = advancedOptions[option];
                break;

              // These process options that look like {top:50, bottom:20}
              case "animIn":
              case "animOut":
              case "cssBefore":
              case "cssAfter":
              case "shuffle":
                settings.opts[option] = eval('(' + advancedOptions[option] + ')');
                break;

              // These options have their own functions.
              case "after":
                // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;

              case "before":
                // transition callback (scope set to element to be shown):     function(currSlideElement, nextSlideElement, options, forwardFlag)
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;

              case "end":
                // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
                settings.opts[option] = function(options) {
                  eval(advancedOptions[option]);
                }
                break;

              case "fxFn":
                // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;

              case "onPagerEvent":
                settings.opts[option] = function(zeroBasedSlideIndex, slideElement) {
                  eval(advancedOptions[option]);
                }
                break;

              case "onPrevNextEvent":
                settings.opts[option] = function(isNext, zeroBasedSlideIndex, slideElement) {
                  eval(advancedOptions[option]);
                }
                break;

              case "pagerAnchorBuilder":
                // callback fn for building anchor links:  function(index, DOMelement)
                settings.opts[option] = function(index, DOMelement) {
                  var returnVal = '';
                  eval(advancedOptions[option]);
                  return returnVal;
                }
                break;

              case "pagerClick":
                // callback fn for pager clicks:    function(zeroBasedSlideIndex, slideElement)
                settings.opts[option] = function(zeroBasedSlideIndex, slideElement) {
                  eval(advancedOptions[option]);
                }
                break;

              case "timeoutFn":
                settings.opts[option] = function(currSlideElement, nextSlideElement, options, forwardFlag) {
                  eval(advancedOptions[option]);
                }
                break;

              case "updateActivePagerLink":
                // callback fn invoked to update the active pager link (adds/removes activePagerClass style)
                settings.opts[option] = function(pager, currSlideIndex) {
                  eval(advancedOptions[option]);
                }
                break;
            }
          }
        }

        // If selected wait for the images to be loaded.
        // otherwise just load the slideshow.
        if (settings.wait_for_image_load) {
          // For IE/Chrome/Opera we if there are images then we need to make
          // sure the images are loaded before starting the slideshow.
          settings.totalImages = $(settings.targetId + ' img').length;
          if (settings.totalImages) {
            settings.loadedImages = 0;

            // Add a load event for each image.
            $(settings.targetId + ' img').each(function() {
              var $imageElement = $(this);
              $imageElement.bind('load', function () {
                Drupal.viewsSlideshowCycle.imageWait(fullId);
              });

              // Removing the source and adding it again will fire the load event.
              var imgSrc = $imageElement.attr('src');
              $imageElement.attr('src', '');
              $imageElement.attr('src', imgSrc);
            });
          }
          else {
            Drupal.viewsSlideshowCycle.load(fullId);
          }
        }
        else {
          Drupal.viewsSlideshowCycle.load(fullId);
        }      
	});
}
})(jQuery);


function SetCookie(cookieName,cookieValue,nDays) {
	 var today = new Date();
	 var expire = new Date();
	 if (nDays==null || nDays==0) nDays=1;
	 expire.setTime(today.getTime() + 3600000*24*nDays);
	 document.cookie = cookieName+"="+escape(cookieValue)
	                 + ";expires="+expire.toGMTString()+'; path=/';
}

function ReadCookie(cookieName) {
	 var theCookie=" "+document.cookie;
	 var ind=theCookie.indexOf(" "+cookieName+"=");
	 if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
	 if (ind==-1 || cookieName=="") return "";
	 var ind1=theCookie.indexOf(";",ind+1);
	 if (ind1==-1) ind1=theCookie.length; 
	 return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}

function open_register_box(buttonType, productID) {
	/*if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
	 var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
	 if (ieversion>=9)	  
		 jQuery.colorbox({innerWidth:520, innerHeight:520, href:'/colorbox/form/user_register_form?destination=wizard&width=auto&height=520'});
	 else if (ieversion<=8)
	  	document.location.href = '/user/register';	 
	} else {
		jQuery.colorbox({innerWidth:520, innerHeight:520, href:'/colorbox/form/user_register_form?destination=wizard&width=auto&height=520'});
	}*/
	//jQuery('#login_hidden_box').colorbox();	
	//jQuery('#login_box_content').click();
	jQuery.ajax({
		url: '/colorbox/form/user_register_form?destination=wizard&width=auto&height=600&type='+buttonType+'&product='+productID,		
		success: function(data) {				
		jQuery.colorbox({html:data, innerWidth:520, innerHeight:600});
			}
		});
}

function drippler_fix_youtube() {	
		jQuery('iframe').each(function() {			
			var url = jQuery(this).attr("src");
			if (url.indexOf('youtube') !== -1) {
				var a_s = '&';			
				if (url.indexOf('?') == -1) {
					a_s = '?';
				}				
				jQuery(this).attr("src",url+a_s+"wmode=transparent");
			}
		});	
}

function post_to_wall_init() {
	if (ReadCookie('block_fb_popup')!=1) {
		jQuery("a[href='/']").click(post_to_wall_handler);
		SetCookie('block_fb_popup' , '1', 1);
		fb_wall_popup = false;
		allow_fb_popup = false;
	}
}

function post_to_wall_handler(event) {
	if (!fb_wall_popup && !('ontouchstart' in window)) {
		FB.getLoginStatus(function(response) { //only for logged in facebook users
			  if (response.status!='unknown') {
				event.preventDefault();
				var obj = {
						//show_error: true,
						method: 'feed',
						link: 'http://drippler.com?utm_medium=Facebook&utm_source=Wall_post&utm_campaign=v1',
						picture: 'http://drippler.com/sites/default/files/hpscreenshot.png',
						name: "I just added my gadgets on Drippler!",
						//caption: "Drippler is cool free service that keeps me updated on my gadgets!",
						description: "Drippler keeps me up to date with everything I need to know about my gadgets: news, rumors, tips, firmware updates, apps, tech-support, manuals & more. Check it out!",
						actions: [{name: 'Check it out!', link:'http://drippler.com?utm_medium=Facebook&utm_source=Wall_post&utm_campaign=v1'}],
						display: 'popup'
				};
				_gaq.push(['_trackEvent','Invitations', 'Registration Popup', 'Popup']);
				FB.ui(obj, fb_wall_callback);
				fb_wall_popup = true;
			  }
		});
	}
}

function fb_wall_callback(response) {
	if (typeof(response)=='undefined' || response==null) {
		_gaq.push(['_trackEvent','Invitations', 'Registration Popup', 'Not Published']);
	} else {
		if (typeof(response['post_id'])!='undefined') {
			_gaq.push(['_trackEvent','Invitations', 'Registration Popup', 'Published']);
		}
	}
	window.location = "/";
}

function fb_wall_product_add_callback(response, action) {
	if (typeof(response)=='undefined' || response==null) {
		_gaq.push(['_trackEvent','Invitations', 'Gadget Add Popup', 'Not Published '+action]);
	} else {
		if (typeof(response['post_id'])!='undefined') {
			_gaq.push(['_trackEvent','Invitations', 'Gadget Add Popup', 'Published '+action]);
		}
	}
}
;
/**
 * drippler_articles_javascript_single_page.js
 */
jQuery(document).ready(function($) {
	//get the full url - like mysitecom/index.htm#home
	//if (data_recived) {		
		//jQuery('.content_pane').html(data_data);
		//drippler_set_analytics_events();			
	//}
});

var data_recived = false;
var data_data = '';

jQuery(document).ready(function() {
//Lets try loading the content before the page is ready
var full_url = document.location.toString();

//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
var parts = full_url.split("#!");
if (parts[1]==null) {
	parts = full_url.split("#");
}
if (parts[1]) {
	var parts = parts[1].split("-");
        var parts = parts[0].split("&");
        var parts = parts[0].split("?");
	var node_id = parts[0];	
	drippler_articles_get_article_single(node_id);
}
});

function drippler_articles_get_article_single(node_id) {	
	if (typeof(node_id) != 'undefined' && node_id != '') {
		var item = jQuery('input:hidden[name=cat_item_nid]').val();
		ajaxUrl = Drupal.settings.basePath+"drippler_ajax/get_article/"+node_id;
		if (item>0) ajaxUrl = ajaxUrl+"/"+item;
		jQuery.ajax({
			  url: ajaxUrl,
			  context: document.body,
			  beforeSend: function() {
				       jQuery('.view-related-products').hide();
  	  	               jQuery('.article-replace').remove();
					 },
			  success: function(data, textStatus, jqXHR){
				  if (jQuery.isFunction(jQuery.autopager))
					  jQuery.autopager('destroy');
				  jQuery('.drips-panel .pane-content:first div:first').prepend(data.replace(/<html>(.*)<\/html>/, "$1"));
				  jQuery('div.pane-category div.related-drips-more').remove();
				  jQuery('#brand div.related-drips-more').remove();
				  data_data = data;
				  data_recived = true;
				  var normal_title = jQuery.trim(jQuery('div.views-field-title').first().text());
				  var check_breads = jQuery('.breadcrumbs').text();
				  check_breads += '&raquo; '+normal_title;					
				  if (check_breads.length >= 114) {
					  //need to substract the title..
					  var substract = check_breads.length - 114;
					  var sub_from_title = normal_title.length - substract;
					  normal_title = normal_title.substr(0,sub_from_title);
					  normal_title += '...';
				  }
				  jQuery('.breadcrumbs').append('<div itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"> &raquo; <a href="' + location.pathname + window.location.hash + '" itemprop="url"><span itemprop="title">'+normal_title+'</span></a></div>');
                                  jQuery('.content_pane').show();
              	  report_outbound_link();
              	  report_analytics('single-page');
				Drupal.flagAnonymousLinks();
				drippler_set_analytics_events();
				Drupal.attachBehaviors(data);
				drippler_set_read_more_links();
				if (typeof(FB) != 'undefined') FB.XFBML.parse(document);
			  }
		});
	}
}
;
/*!
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
// 
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub       - http://github.com/cowboy/jquery-hashchange/
// Source       - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified)   - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
// 
// About: License
// 
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
// 
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
// 
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
//                   Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests      - http://benalman.com/code/projects/jquery-hashchange/unit/
// 
// About: Known issues
// 
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
// 
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
// 
// Also note that should a browser natively support the window.onhashchange 
// event, but not report that it does, the fallback polling loop will be used.
// 
// About: Release History
// 
// 1.3   - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
//         "removable" for mobile-only development. Added IE6/7 document.title
//         support. Attempted to make Iframe as hidden as possible by using
//         techniques from http://www.paciellogroup.com/blog/?p=604. Added 
//         support for the "shortcut" format $(window).hashchange( fn ) and
//         $(window).hashchange() like jQuery provides for built-in events.
//         Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
//         lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
//         and <jQuery.fn.hashchange.src> properties plus document-domain.html
//         file to address access denied issues when setting document.domain in
//         IE6/7.
// 1.2   - (2/11/2010) Fixed a bug where coming back to a page using this plugin
//         from a page on another domain would cause an error in Safari 4. Also,
//         IE6/7 Iframe is now inserted after the body (this actually works),
//         which prevents the page from scrolling when the event is first bound.
//         Event can also now be bound before DOM ready, but it won't be usable
//         before then in IE6/7.
// 1.1   - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
//         where browser version is incorrectly reported as 8.0, despite
//         inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0   - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
//         window.onhashchange functionality into a separate plugin for users
//         who want just the basic event & back button support, without all the
//         extra awesomeness that BBQ provides. This plugin will be included as
//         part of jQuery BBQ, but also be available separately.

(function($,window,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  // Reused string.
  var str_hashchange = 'hashchange',
    
    // Method / object references.
    doc = document,
    fake_onhashchange,
    special = $.event.special,
    
    // Does the browser support window.onhashchange? Note that IE8 running in
    // IE7 compatibility mode reports true for 'onhashchange' in window, even
    // though the event isn't supported, so also test document.documentMode.
    doc_mode = doc.documentMode,
    supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
  
  // Get location.hash (or what you'd expect location.hash to be) sans any
  // leading #. Thanks for making this necessary, Firefox!
  function get_fragment( url ) {
    url = url || location.href;
    return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
  };
  
  // Method: jQuery.fn.hashchange
  // 
  // Bind a handler to the window.onhashchange event or trigger all bound
  // window.onhashchange event handlers. This behavior is consistent with
  // jQuery's built-in event handlers.
  // 
  // Usage:
  // 
  // > jQuery(window).hashchange( [ handler ] );
  // 
  // Arguments:
  // 
  //  handler - (Function) Optional handler to be bound to the hashchange
  //    event. This is a "shortcut" for the more verbose form:
  //    jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
  //    all bound window.onhashchange event handlers will be triggered. This
  //    is a shortcut for the more verbose
  //    jQuery(window).trigger( 'hashchange' ). These forms are described in
  //    the <hashchange event> section.
  // 
  // Returns:
  // 
  //  (jQuery) The initial jQuery collection of elements.
  
  // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
  // $(elem).hashchange() for triggering, like jQuery does for built-in events.
  $.fn[ str_hashchange ] = function( fn ) {
    return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
  };
  
  // Property: jQuery.fn.hashchange.delay
  // 
  // The numeric interval (in milliseconds) at which the <hashchange event>
  // polling loop executes. Defaults to 50.
  
  // Property: jQuery.fn.hashchange.domain
  // 
  // If you're setting document.domain in your JavaScript, and you want hash
  // history to work in IE6/7, not only must this property be set, but you must
  // also set document.domain BEFORE jQuery is loaded into the page. This
  // property is only applicable if you are supporting IE6/7 (or IE8 operating
  // in "IE7 compatibility" mode).
  // 
  // In addition, the <jQuery.fn.hashchange.src> property must be set to the
  // path of the included "document-domain.html" file, which can be renamed or
  // modified if necessary (note that the document.domain specified must be the
  // same in both your main JavaScript as well as in this file).
  // 
  // Usage:
  // 
  // jQuery.fn.hashchange.domain = document.domain;
  
  // Property: jQuery.fn.hashchange.src
  // 
  // If, for some reason, you need to specify an Iframe src file (for example,
  // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
  // do so using this property. Note that when using this property, history
  // won't be recorded in IE6/7 until the Iframe src file loads. This property
  // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
  // compatibility" mode).
  // 
  // Usage:
  // 
  // jQuery.fn.hashchange.src = 'path/to/file.html';
  
  $.fn[ str_hashchange ].delay = 50;
  /*
  $.fn[ str_hashchange ].domain = null;
  $.fn[ str_hashchange ].src = null;
  */
  
  // Event: hashchange event
  // 
  // Fired when location.hash changes. In browsers that support it, the native
  // HTML5 window.onhashchange event is used, otherwise a polling loop is
  // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
  // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
  // compatibility" mode), a hidden Iframe is created to allow the back button
  // and hash-based history to work.
  // 
  // Usage as described in <jQuery.fn.hashchange>:
  // 
  // > // Bind an event handler.
  // > jQuery(window).hashchange( function(e) {
  // >   var hash = location.hash;
  // >   ...
  // > });
  // > 
  // > // Manually trigger the event handler.
  // > jQuery(window).hashchange();
  // 
  // A more verbose usage that allows for event namespacing:
  // 
  // > // Bind an event handler.
  // > jQuery(window).bind( 'hashchange', function(e) {
  // >   var hash = location.hash;
  // >   ...
  // > });
  // > 
  // > // Manually trigger the event handler.
  // > jQuery(window).trigger( 'hashchange' );
  // 
  // Additional Notes:
  // 
  // * The polling loop and Iframe are not created until at least one handler
  //   is actually bound to the 'hashchange' event.
  // * If you need the bound handler(s) to execute immediately, in cases where
  //   a location.hash exists on page load, via bookmark or page refresh for
  //   example, use jQuery(window).hashchange() or the more verbose 
  //   jQuery(window).trigger( 'hashchange' ).
  // * The event can be bound before DOM ready, but since it won't be usable
  //   before then in IE6/7 (due to the necessary Iframe), recommended usage is
  //   to bind it inside a DOM ready handler.
  
  // Override existing $.event.special.hashchange methods (allowing this plugin
  // to be defined after jQuery BBQ in BBQ's source code).
  special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
    
    // Called only when the first 'hashchange' event is bound to window.
    setup: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) { return false; }
      
      // Otherwise, we need to create our own. And we don't want to call this
      // until the user binds to the event, just in case they never do, since it
      // will create a polling loop and possibly even a hidden Iframe.
      $( fake_onhashchange.start );
    },
    
    // Called only when the last 'hashchange' event is unbound from window.
    teardown: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) { return false; }
      
      // Otherwise, we need to stop ours (if possible).
      $( fake_onhashchange.stop );
    }
    
  });
  
  // fake_onhashchange does all the work of triggering the window.onhashchange
  // event for browsers that don't natively support it, including creating a
  // polling loop to watch for hash changes and in IE 6/7 creating a hidden
  // Iframe to enable back and forward.
  fake_onhashchange = (function(){
    var self = {},
      timeout_id,
      
      // Remember the initial hash so it doesn't get triggered immediately.
      last_hash = get_fragment(),
      
      fn_retval = function(val){ return val; },
      history_set = fn_retval,
      history_get = fn_retval;
    
    // Start the polling loop.
    self.start = function() {
      timeout_id || poll();
    };
    
    // Stop the polling loop.
    self.stop = function() {
      timeout_id && clearTimeout( timeout_id );
      timeout_id = undefined;
    };
    
    // This polling loop checks every $.fn.hashchange.delay milliseconds to see
    // if location.hash has changed, and triggers the 'hashchange' event on
    // window when necessary.
    function poll() {
      var hash = get_fragment(),
        history_hash = history_get( last_hash );
      
      if ( hash !== last_hash ) {
        history_set( last_hash = hash, history_hash );
        
        $(window).trigger( str_hashchange );
        
      } else if ( history_hash !== last_hash ) {
        location.href = location.href.replace( /#.*/, '' ) + history_hash;
      }
      
      timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
    };
    
    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    $.browser.msie && !supports_onhashchange && (function(){
      // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
      // when running in "IE7 compatibility" mode.
      
      var iframe,
        iframe_src;
      
      // When the event is bound and polling starts in IE 6/7, create a hidden
      // Iframe for history handling.
      self.start = function(){
        if ( !iframe ) {
          iframe_src = $.fn[ str_hashchange ].src;
          iframe_src = iframe_src && iframe_src + get_fragment();
          
          // Create hidden Iframe. Attempt to make Iframe as hidden as possible
          // by using techniques from http://www.paciellogroup.com/blog/?p=604.
          iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
            
            // When Iframe has completely loaded, initialize the history and
            // start polling.
            .one( 'load', function(){
              iframe_src || history_set( get_fragment() );
              poll();
            })
            
            // Load Iframe src if specified, otherwise nothing.
            .attr( 'src', iframe_src || 'javascript:0' )
            
            // Append Iframe after the end of the body to prevent unnecessary
            // initial page scrolling (yes, this works).
            .insertAfter( 'body' )[0].contentWindow;
          
          // Whenever `document.title` changes, update the Iframe's title to
          // prettify the back/next history menu entries. Since IE sometimes
          // errors with "Unspecified error" the very first time this is set
          // (yes, very useful) wrap this with a try/catch block.
          doc.onpropertychange = function(){
            try {
              if ( event.propertyName === 'title' ) {
                iframe.document.title = doc.title;
              }
            } catch(e) {}
          };
          
        }
      };
      
      // Override the "stop" method since an IE6/7 Iframe was created. Even
      // if there are no longer any bound event handlers, the polling loop
      // is still necessary for back/next to work at all!
      self.stop = fn_retval;
      
      // Get history by looking at the hidden Iframe's location.hash.
      history_get = function() {
        return get_fragment( iframe.location.href );
      };
      
      // Set a new history item by opening and then closing the Iframe
      // document, *then* setting its location.hash. If document.domain has
      // been set, update that as well.
      history_set = function( hash, history_hash ) {
        var iframe_doc = iframe.document,
          domain = $.fn[ str_hashchange ].domain;
        
        if ( hash !== history_hash ) {
          // Update Iframe with any initial `document.title` that might be set.
          iframe_doc.title = doc.title;
          
          // Opening the Iframe's document after it has been closed is what
          // actually adds a history entry.
          iframe_doc.open();
          
          // Set document.domain for the Iframe document as well, if necessary.
          domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
          
          iframe_doc.close();
          
          // Update the Iframe's hash, for great justice.
          iframe.location.hash = hash;
        }
      };
      
    })();
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    return self;
  })();
  
})(jQuery,this);;
/*
 * jQuery Form Example Plugin 1.4.1
 * Populate form inputs with example text that disappears on focus.
 *
 * e.g.
 *  $('input#name').example('Bob Smith');
 *  $('input[@title]').example(function() {
 *    return $(this).attr('title');
 *  });
 *  $('textarea#message').example('Type your message here', {
 *    className: 'example_text'
 *  });
 *
 * Copyright (c) Paul Mucur (http://mucur.name), 2007-2008.
 * Dual-licensed under the BSD (BSD-LICENSE.txt) and GPL (GPL-LICENSE.txt)
 * licenses.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
(function(A){A.fn.example=function(E,C){var D=A.isFunction(E);var B=A.extend({},C,{example:E});return this.each(function(){var F=A(this);if(A.metadata){var G=A.extend({},A.fn.example.defaults,F.metadata(),B)}else{var G=A.extend({},A.fn.example.defaults,B)}if(!A.fn.example.boundClassNames[G.className]){A(window).unload(function(){A("."+G.className).val("")});A("form").submit(function(){A(this).find("."+G.className).val("")});A.fn.example.boundClassNames[G.className]=true}if(A.browser.msie&&!F.attr("defaultValue")&&(D||F.val()==G.example)){F.val("")}if(F.val()==""&&this!=document.activeElement){F.addClass(G.className);F.val(D?G.example.call(this):G.example)}F.focus(function(){if(A(this).is("."+G.className)){A(this).val("");A(this).removeClass(G.className)}});F.blur(function(){if(A(this).val()==""){A(this).addClass(G.className);A(this).val(D?G.example.call(this):G.example)}})})};A.fn.example.defaults={className:"example"};A.fn.example.boundClassNames=[]})(jQuery);;

