var JilCompliance = function () {
	var $ = jQuery;
	return {
		init: function() {
			var instance = this;

			//instance.handleSearchForm();
			//instance.handleLastChild();
			//instance.communityMenu();
			instance.loginFormFix();
		},

		handleSearchForm: function() {
			var searchForm = $('#banner .search');

			var searchInput = searchForm.find('input[type=image]');
			var searchLink = $('<a class="search-input-link" href="javascript:;"></a>');

			searchLink.click(
				function() {
					$(this).parents('form')[0].submit();
				}
			);

			searchInput.hide();
			searchInput.before(searchLink);
		},

		handleLastChild: function () {
			var instance = this;

			$('#footer ul li:last').addClass('last-child');
		},

		communityMenu: function() {
			$(" #navbar ul ul ").css({display: "none"}); // Opera Fix
			$(" #navbar li ").hoverIntent(
				{
					interval: 25,
					timeout: 100,
					over: function () {
						//$(this).find('ul:first:hidden').css({visibility: "visible", display: "none"}).show(400);
						$(this).find('ul:first:hidden').css({visibility: "visible", display: "none"}).slideDown(400);
					},
					out: function () {
						$(this).find('ul:first').slideUp(100);
					}
				}
			);
		},
		
		loginFormFix: function(){
			$('.default-value').each(function() {
			    var default_value = this.value;
			    $(this).focus(function() {
			        if(this.value == default_value) {
			            this.value = '';
						$(this).css('color', '#333');
			        }
			    });
			    $(this).blur(function() {
			        if(this.value == '') {
						$(this).css('color', '#666');
			            this.value = default_value;
			        }
			    });
			});
		}
	};
}();




jQuery(document).ready(

	/*
	This function gets loaded when all the HTML, not including the portlets, is
	loaded.
	*/

	function() {		
		jQuery('ul.sf-menu').superfish();
		//JilCompliance.init();			
		
		var error_param = getRequestParameterFromURL( 'e' );
		jQuery('.termsid').click(function() {
			OpenTermsAndCondition(false);
			return false;
		});
		jQuery('.termsjil').click(function() {
			OpenJILTermsAndCondition();
			return false;
		});
		jQuery('#forgot-password-button').click(function() {
			jilSubmitForgotPassword();
		});
		jQuery('#close-forgot-password-button').click(function() {
			jilHideForgotPassword();
		});		
	}
);

function jilSubmitForgotPassword(){
		if (jQuery("#jil-forgot-password-email").val() != jQuery("#jil-forgot-password-email").attr('defaultval')){
				jQuery.ajax({
 					url: "/retrievePassword",
					dataType: 'json',
					type: 'post',
					cache: false,
					data: {email: jQuery("#jil-forgot-password-email").val()},
					success: function(data) {
							if (data.errorcode == "success"){
								var successDiv = jQuery('#jil-forgot-password-success');
								if(jQuery('#jil-forgot-password-success .dwp-Red')){
									jQuery('#jil-forgot-password-success .dwp-Red').remove();
								}
								successDiv.append('<span class="dwp-Red">' + successDiv.attr('msg') +'</span>');
								setTimeout("jQuery('#jil-forgot-password-success .dwp-Red').remove()",20000);
								document.getElementById('jil-forgot-password-success').style.display = 'block';	
								document.getElementById('jil-forgot-password-error').style.display = 'none';
								document.getElementById('jil-forgot-password-admin-success').style.display = 'none';
								
							}else {
								if ((data.errorcode == 230) || (data.errorcode == 101)){
									if(jQuery('#jil-forgot-password-error .dwp-Red')){
										jQuery('#jil-forgot-password-error .dwp-Red').remove();
									}
									var errorDiv = jQuery('#jil-forgot-password-error');
									errorDiv.append('<span class="dwp-Red">' + errorDiv.attr('msg') +'</span>');
									setTimeout("jQuery('#jil-forgot-password-error .dwp-Red').remove()",20000);								
									document.getElementById('jil-forgot-password-error').style.display = 'block';
									document.getElementById('jil-forgot-password-success').style.display = 'none';
									document.getElementById('jil-forgot-password-admin-success').style.display = 'none';
								}
								else if (data.errorcode == 1301){
									var errorDiv = jQuery('#jil-forgot-password-admin-success');
									errorDiv.append('<span class="dwp-Red">' + errorDiv.attr('msg') +'</span>');
									setTimeout("jQuery('#jil-forgot-password-admin-success .dwp-Red').remove()",20000);								
									document.getElementById('jil-forgot-password-admin-success').style.display = 'block';
									document.getElementById('jil-forgot-password-success').style.display = 'none';
									document.getElementById('jil-forgot-password-error').style.display = 'none';
								}								
							}
					 },
					failure: function() {
						//need to handle failure
					}
				 });
		}
}


Liferay.Portlet.ready(

	/*
	This function gets loaded after each and every portlet on the page.

	portletId: the current portlet's id
	jQueryObj: the jQuery wrapped object of the current portlet
	*/

	function(portletId, jQueryObj) {
	}
);

jQuery(document).last(

	/*
	This function gets loaded when everything, including the portlets, is on
	the page.
	*/

	function() {
		if(!themeDisplay.isSignedIn()){
			jQuery('.protectedlink').each(function() {
			    var $t = jQuery(this);
    			    $t.after('<span class="jil-Link-Disabled">' +$t.text()+ '</span>');
    			    $t.remove();
			});
		}
		setTimeout("hideErrorMessages()",20000);
	}
);

function hideErrorMessages(){
	jQuery('.portlet-msg-error').each(function(){	
		jQuery(this).remove();
	});
	jQuery('.dwp-Red').each(function(){	
		jQuery(this).remove();
	});
	jQuery('.thankyou-msg').each(function(){	
		jQuery(this).remove();
	});	
}


function closePopup(){
   jQuery('.ui-dialog-overlay').each(function(){	
		jQuery(this).remove();
	});
	jQuery('.ui-dialog').each(function(){	
		jQuery(this).remove();
	});

}


function jilShowForgotPassword() {
	document.getElementById('jil-forgot-password-popup').style.display = 'block';
	document.getElementById('jil-forgot-password-error').style.display = 'none';
	document.getElementById('jil-forgot-password-success').style.display = 'none';
	var emailLabel = jQuery("#jil-forgot-password-email").attr("value");
	jQuery("#jil-forgot-password-email").click(function() {
		jQuery("#jil-forgot-password-email").val("");
	});
	
	jQuery("#jil-forgot-password-email").blur(function() {
		if(jQuery("#jil-forgot-password-email").attr("value").length == 0 ){
			jQuery("#jil-forgot-password-email").val(emailLabel);
		}
	});
}

function jilHideForgotPassword() {
	document.getElementById('jil-forgot-password-email').value = '';
	document.getElementById('jil-forgot-password-popup').style.display = 'none';
}

function submit_search_form(){
	var submit_form = document.getElementById("universal_search_form");
	var url = "/web/jil/home";
    submit_form.action = url + "?p_p_id=3&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&_3_struts_action=%2Fsearch%2Fsearch";
    submit_form.submit();
}
function getRequestParameterFromURL( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


function callParentPopup(url,OkButton){
       
    var contnentUrl="/listener/image/"+returnContentId(url);
    
       var imageUrl='<table cellspacing="10" cellpadding="0" ><tbody>'+
 		    '<tr><td align="right">'+
			'<button tabindex="0" type="button" class="jil-button dwp-LargeMarginRight" onclick="Liferay.Popup.close(this);">'+OkButton+
			'</button></td></tr>'+
 		    '<tr>'+
			'<td align="right" style="vertical-align: top;"><img src='+contnentUrl+' id="imagepk1" class="gwt-Image"/></td></tr></tbody></table>';
 	  var  widthPopup=jQuery("#imagepk1").width();
 		  	
 		var popup = Liferay.Popup(
				{
					modal: true,
					position: ['center', 150],
					message:  imageUrl,
					width: widthPopup
					
				}
			);
			jQuery('.ui-dialog-overlay').css('opacity',0); 	 
            jQuery('.ui-dialog-titlebar').css('display','none'); 	
}


function returnContentId(url){
  return url.substring(url.lastIndexOf("//")+2,url.length);
}


 var popuptnc;
function OpenTermsAndCondition(termsName) {
 popuptnc = Liferay.Popup({
		title: 'TermsAndCondtion',
		modal: true,
		position: ['center', 150],
		url:  '/web/jil/home?p_p_id=popupportlet_WAR_popupportlet&p_p_lifecycle=0&p_p_state=exclusive&_popupportlet_WAR_popupportlet_jspPage=tnc.jsp&acceptTerms='+termsName,
		width: 900,
		resizable:false,
		draggable:false
	});
	return false;
}
function OpenJILTermsAndCondition() {
		popuptnc = Liferay.Popup({
			title: 'TermsAndCondtion',
			modal: true,
			position: ['center', 150],
		    url:  '/web/jil/home?p_p_id=popupportlet_WAR_popupportlet&p_p_lifecycle=0&p_p_state=exclusive&_popupportlet_WAR_popupportlet_jspPage=tnc.jsp&termsName=jil_terms_and_conditions&t='+today.getTime(),
		    width: 900,
		    resizable:false,
			draggable:false
		});
		return false;
}

//This method opens a terms and condition for the given operator
function OpenOperatorTermsAndCondition(operator) {
		popuptnc = Liferay.Popup({
			title: 'TermsAndCondtion',
			modal: true,
			position: ['center', 150],
		    url:  '/web/jil/home?p_p_id=popupportlet_WAR_popupportlet&p_p_lifecycle=0&p_p_state=exclusive&_popupportlet_WAR_popupportlet_jspPage=tnc.jsp&termsName='+ operator+'&t='+today.getTime(),
		    width: 900,
		    resizable:false,
			draggable:false
		});
		return false;
}

//This method opens a terms and condition for the given operator with buttons
function OpenOperatorTermsAndConditionWithAcceptEnabled(operator) {
		popuptnc = Liferay.Popup({
			title: 'TermsAndCondtion',
			modal: true,
			position: ['center', 150],
		    url:  '/web/jil/home?p_p_id=popupportlet_WAR_popupportlet&p_p_lifecycle=0&p_p_state=exclusive&_popupportlet_WAR_popupportlet_jspPage=tnc.jsp&termsName='+ operator + '&acceptTerms=true&showTerms=true&t='+today.getTime() ,
		    width: 900,
		    resizable:false,
			draggable:false
		});
		return false;
}

function OpenOperatorTermsAndConditionWithAcceptDisabled(operator) {
	popuptnc = Liferay.Popup({
		title: 'TermsAndCondtion',
		modal: true,
		position: ['center', 150],
	    url:  '/web/jil/home?p_p_id=popupportlet_WAR_popupportlet&p_p_lifecycle=0&p_p_state=exclusive&_popupportlet_WAR_popupportlet_jspPage=tnc.jsp&termsName='+ operator + '&acceptTerms=false&showTerms=true&t='+today.getTime() ,
	    width: 900,
	    resizable:false,
		draggable:false
	});
	return false;
}

function cancelPublishPopup(okBtn,noBtn,Mssg,isEdit){

  var warn_msg = Mssg+'<br /><br />'
					+ '<input id="ok_btn_warn" value='+okBtn+' type="button" />&nbsp;&nbsp;'
					+ '<input id="no_btn_warn" value='+noBtn+' type="button" />';
	var popup = Liferay.Popup({
				message: warn_msg,
				modal: true,
				position:['center',180],
				width:300				
		});
		jQuery('.ui-dialog-overlay').css('opacity',0); 
		jQuery('.ui-dialog-titlebar').css('display','none');	
		
		
		// when 'no' is clicked
		jQuery("#no_btn_warn").click(function() {
			Liferay.Popup.close(this);
		});
		
		// when 'ok' is clicked
		jQuery("#ok_btn_warn").click(function(){
			Liferay.Popup.close(this);
			url=window.parent.location.protocol+"//"+window.parent.location.host;
			if(isEdit){
				window.parent.location.href=url+"/web/jil/my-widgets";
			}else{
			 	window.parent.location.href=url+"/web/jil/publish"; 	
			}	
		});	
}

/**
*
*  URL encode / decode
*
**/
 
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
