var arr_Industry = [];
var arr_SiteUrls = [];
var arr_SiteNames = [];

$(document).ready(function(){
	$('div.comp-forum-post:odd').addClass('alt');
	$("ol.comp-2ndlevellisting li.category:even").addClass("odd");
	$("input[@type=checkbox]").addClass("checkbox");
	$("input[@type=radio]").addClass("radio");	
	$("input[@type=text]").addClass("text");		
	$("input[@type=password]").addClass("text");				
  	initTemplate()
	initAlertMe();
	initGallery();
	initSearchResults();
	initRegistrationForm();	
	initToolTips();
	
   /* new - for home poll  */
   // apply to all png images 
   $('img[@src$=.png]').ifixpng(); 
   $('div.id-template-col1 a.ms-toolbar').aspx('<span class="button-end">' + $('a.ms-toolbar').aspx() + '</span>');
	 $('div.id-template-col3 a.ms-toolbar').aspx('<span class="button-end">' + $('a.ms-toolbar').aspx() + '</span>');

	if($("div.comp-homepanel").length > 0) {
	   /* ok... bit dodgy, but sharepoint is struggling to set the height.. local version works without this timeout... */
	   setInterval(initHomePage,100);
	   initHomePage();
	} // end check for element	
});

initHomePage = function() {
	
	/* check if the elements are there... ok I'm only checking one... */
	
		
		
		
		 var height1 = $("li.comp-homepanel1 dl").get(0).offsetHeight;	
		 var height2 = $("li.comp-homepanel2 dl").get(0).offsetHeight;	
		 var height3 = $("li.comp-homepanel3 dl").get(0).offsetHeight;
		 var height4 = $("li.comp-homepanel4 dl").get(0).offsetHeight;
		 
		 /*alert(height1 + " " + height2 + " " + height3 + " " + height4);*/

		if ($.browser.msie && $.browser.version < 7) {		 
			 /* top panels */
			
			if(height1 > height2) {
				$("li.comp-homepanel2 dl").css("height",height1 + "px");
			} else {
				$("li.comp-homepanel1 dl").css("height",height2 + "px");
			}
			/* bottom panels */
			if(height3 > height4) {
				$("li.comp-homepanel4 dl").css("height",height3 + "px");
			} else {
				$("li.comp-homepanel3 dl").css("height",height4 + "px");
			}
		} else {
			 /* top panels */
			if(height1 > height2) {
				$("li.comp-homepanel2 dl").css("min-height",height1 + "px");
			} else {
				$("li.comp-homepanel1 dl").css("min-height",height2 + "px");
			}
			/* bottom panels */
			if(height3 > height4) {
				$("li.comp-homepanel4 dl").css("min-height",height3 + "px");
			} else {
				$("li.comp-homepanel3 dl").css("min-height",height4 + "px");
			}			
		} // end browser test


} // end initHome

initToolTips = function() {

  $("fieldset li span.help a").each(function() { 
	$(this).Tooltip({
	   delay: 0,
	   top: 0,
	   left: 20,
	   showURL: false
	});
   });
}

function initSearchResults() {
   $("div.location a").each(function() {
      var string_Text = $(this).aspx();
	  string_Text = string_Text.replace("http://","");
	  string_Text = string_Text.replace("https://","");
	  string_Text = string_Text.replace("<b>","");
	  string_Text = string_Text.replace("</b>","");
	  string_Text = string_Text.replace("<B>","");
	  string_Text = string_Text.replace("</B>","");
	  var arr_Text = string_Text.split("/");
	  var outputLocation = "";
	  var stringDivider = "";
	  for(key in arr_Text) {
	     
	     
		 if(arr_Text[key] == "Pages" || arr_Text[key] == "Forms" || arr_Text[key] == "_layouts" || arr_Text[key] == "Lists") {
		    break;
		 }
		 if(key > 0) {	 
		    outputLocation += stringDivider;   
		    outputLocation += arr_Text[key];
			stringDivider = "/";
		 }
		 
	  } // end for loop
	  
	  outputLocation = outputLocation.toUpperCase();
	  
	  for(key in arr_SiteUrls) {
	  	if(arr_SiteUrls[key] == outputLocation) {
	  		outputLocation = arr_SiteNames[key];
	  		break;
	  	}
	  }
	  	  		
	  if (outputLocation == "")
	  	outputLocation = "Home"
	  $(this).aspx(outputLocation);
	  
   });	
}

/* init gallery */
function initGallery() {
	$("ul.gallery li.image").each(function() {
	   $("a",this).click(function(){
			$("ul.gallery li.image a").removeClass("selected");
			$(this).addClass("selected");		
			$(this).parent().find("input[@type=radio]").click();

			$("#myImageServerText").val($(this).parent().find("input[@type=radio]").val());
			$("li.uploadimage input[@type=file]").val("");
			return false;							   							  
		});
	});
	$("li.uploadimage input[@type=file]").change(function() {
		$("ul.gallery li.image a").removeClass("selected");
		$("ul.gallery li.image input[@type=radio]").attr("checked",false);	
	});
}
/* 
initialisation function
=================================================
*/

function initTemplate() {
	
	/* make the text boxes select all text when clicked on */
	$("div.comp-template-login li.password input").click(function() {
		textFocus(this);
	});
	$("div.comp-template-login li.email input").click(function() {
		textFocus(this);					   
	});
	
	/* smooth scroll # links */
	smoothLocalScroll();
}

function initAlertMe() {
  $("div.comp-alert-me-alerts input.delete").click(function() {
   //   return confirm("are you sure?");
  });
}

function closeGallery(imageURL) {
	if (imageURL != '')
	{
	$("li.screenimage input[@type=text]").attr("value",imageURL);
	$("li.screenimage input[@type=text]").get(0).extModified();
	}
	
    /* manually remove the modal window... because opera is a funny thing... */	
	currentModal.dialog.overlay.remove();
    currentModal.dialog.overlay = null;
	currentModal.dialog.container.remove();
	if (currentModal.dialog.iframe) {
		currentModal.dialog.iframe.remove();
	}	
	currentModal.dialog = new Object;
	currentModal.unbindEvents();
}

function createOptions(arr_options) {

   if(!arr_options) {
	   return false;
   } else {
	   var outputHTML = "<option>-- Please Select --</option>";   

	   for(key in arr_options) {

		  outputHTML += "<option value='" + arr_options[key] + "'>";
		  outputHTML += arr_options[key];		  
		  outputHTML += "</option>";

	
	   }
	  return outputHTML;	   
   }

};

/* relates to industry selects ==================== */

function manageSelectFields(groupID, objTarget, preselectedRefinedIndustry) {

	  var currentGeneratedOptions = createOptions(arr_Industry[groupID]);
	  if(currentGeneratedOptions) {
		  $(objTarget).attr("disabled",false);
		  $(objTarget).aspx(currentGeneratedOptions);
         if(preselectedRefinedIndustry) {
		 
			$(objTarget).find("option[@value=" + preselectedRefinedIndustry + "]").each(function() {
			   makeSelected(this);
			});
		 } else {
			 $(objTarget).find("option:first-child").attr("selected",true);
		 }	
	  } else {
		  $(objTarget).attr("disabled",true);
		  $(objTarget).aspx("<option>-- Please Select --</option>");			  
	  }
} // end function
   

/* relates to industry selects ================================  */ 
function returnRefinedGroup(needle,haystack) {
	for(var key in haystack) {
		 for(key2 in haystack[key]){
			if(haystack[key][key2] == needle) {
				  return key;
			}
		 }
	}
	return false;
}

function initRegistrationForm() {
	
 /* browse button on forum registration page
  ================================================*/ 
  $("li.screenimage").each(function() {
	   var browseButton =  $(this).find("a.browse");

	   $(this).find("input").each(function() {
										   
			browseControl($(this),browseButton);
			
			$(this).attr("readonly",true);
			
			// behaviours 
			$(this).keyup(function() {
				browseControl($(this),browseButton);
			});
		
			
			this.extModified = function() {
				browseControl($(this),browseButton);
			}

			// functions
			function browseControl(obj,browseButton) {
				if($(obj).val()) {
					$(browseButton).aspx("Change Image");
					$(browseButton).addClass("change");						
				} else {
					$(browseButton).aspx("Browse");
					$(browseButton).removeClass("change");					
				}				
			}


		});

	  $(this).find("a.browse").click(function() {
		//window.open(this.href,"browse","width=575,height=600,resizable=yes,toolbar=no,status=no,menubar=no");		
		
		currentModal = $.modal('<div id="gallery-browse"><iframe frameborder=0 scrolling=no src="' + this.href + '"></iframe></div>',
				{overlay: 30}		
		);

		return false;
	  });
	  
	    }); // end screenimage

	  
	  controlFieldState = function(objsrc,objtarget) {
		   var currentSelection = $(objsrc).find("option:selected").val();
		   var currentFirstOption = $(objsrc).find("option:first-child").val();
		   

		   if(currentSelection != "Australia (default value)") {
				$(objtarget).find("option:last-child").each(function() {
						makeSelected(this);
						
					});
		   } else {

			   var lastOption = $(objtarget).find("option:last-child").val();
			   var selectedOption = $(objtarget).find("option:selected").val();

			   if(lastOption == selectedOption) {
								   
				   $(objtarget).find("option:first-child").each(function() {
						makeSelected(this);
					});
			   }
		   }

	  } // end controlFieldState
	  
	  controlFieldCountry = function(objsrc,objtarget) {
		  
		   var currentSelection = $(objsrc).find("option:selected").val(); 
		   var currentLastOption = $(objsrc).find("option:last-child").val();
		   if(currentSelection != currentLastOption) {
	   
			   $(objtarget).find("option[@value=Australia (default value)]").each(function() {
					makeSelected(this);
				});
			   
		   }
	  }
	  
	  controlFieldState($(".comp-profile-form .country select"),$(".comp-profile-form .state select"));	
	  
	  $(".comp-profile-form .country select").change(function() {
	      controlFieldState(this,$(".comp-profile-form .state select"));																  
	  });
	  $(".comp-profile-form .state select").change(function() {														
	      controlFieldCountry(this,$(".comp-profile-form .country select"));																  
	  });	
	  
	  setupIndustryFields();

}

function setupIndustryFields() {
	
	//setupIndustryFields();
/**/  var industrySelect = $("li.industry select");
   var refinedIndustrySelect = $(".refinerindustry select");

   industrySelect.change(function() {
	  manageSelectFields($(this).find("option:selected").val(), refinedIndustrySelect);
   });
   
   if($(".refinerindustry select >").size() <= 1) {
	  manageSelectFields($(industrySelect).find("option:selected").val(), refinedIndustrySelect);
   }
   
   // set the value to a hidden element
   refinedIndustrySelect.change(function() {
	  $("#Refine").find("input").val($(this).find("option:selected").val());
   });
   
   var preselectedRefinedIndustry = $("#RefineReadonly").find("input").val();
   var preselectedRefinedGroup = returnRefinedGroup(preselectedRefinedIndustry,arr_Industry);

   if(preselectedRefinedGroup !== false) {
		manageSelectFields(preselectedRefinedGroup, refinedIndustrySelect, preselectedRefinedIndustry);
   }
	
}



function textFocus(obj) {
   var currentOject = $(obj);
   currentOject.select();
}
function smoothLocalScroll() {
	  /* scroll to smoothly...*/
  $('.comp-back-to-top a[href*=#]').click(function() {
	if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
		
	  var $target = $(this.hash);
	  $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
	 
	  if ($target.length) {
		var targetOffset = $target.offset().top;
		   $('html,body').animate({scrollTop: targetOffset}, 500);
	   return false;
	     
	  }
	  
	}
  }); 
}


function makeSelected(obj) {

	if($.browser.msie) {
	   obj.setAttribute('selected',true);
	} else {
	   obj.selected = true;
	}
}


// Check DOM readiness in IE - Used here to activate the "Refine your Industry" select pre-population in IE6 when editing profile.
if (document.all && !window.opera){ //Crude test for IE
//Define a "blank" external JavaScript tag
  document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="https://about:blank"><\/script>')
  var contentloadtag=document.getElementById("contentloadtag")
  contentloadtag.onreadystatechange=function(){
	if (this.readyState=="complete")
	  setupIndustryFields()
  }
}
