var assignerror="";
var assingvar ="";
var errors;
var isDelete="";
var errorpageurl= ""; 

function createformSubmit(){

	var accept = document.getElementById("create");
	var photo_accept 	= document.getElementById("photo-submit");
	var photo_change 	= document.getElementById("photo-change");
	var img_change   	= document.getElementById("filename");
	var catg_code    	= document.getElementById("category_cd");
	var subcat_code     = document.getElementById("subcategory_cd");
	
	if(photo_accept!=null){
		photo_accept.onclick = function() { photo_submit();}
	}
	if(photo_change!=null){
		photo_change.onclick = function() { photo_submit();}
	}
	if(img_change!=null){
		img_change.onchange = function() { changeButtonView();}
	}
	
	if(accept!=null){
		accept.onclick = function() { validateFormFields(); return false;}
		
	}
	
	if(catg_code!=null){
		catg_code.onchange = function() { getSubcategory(); checkForAdult();}
	}
	if(subcat_code!=null){
		subcat_code.onchange = function() {checkForAdult();}
	}
	
	
}

function whichBrowser() {
    var agt=navigator.userAgent.toLowerCase();
    if (agt.indexOf("opera") != -1) return 'Opera';
    if (agt.indexOf("staroffice") != -1) return 'Star Office';
    if (agt.indexOf("webtv") != -1) return 'WebTV';
    if (agt.indexOf("beonex") != -1) return 'Beonex';
    if (agt.indexOf("chimera") != -1) return 'Chimera';
    if (agt.indexOf("netpositive") != -1) return 'NetPositive';
    if (agt.indexOf("phoenix") != -1) return 'Phoenix';
    if (agt.indexOf("firefox") != -1) return 'Firefox';
    if (agt.indexOf("safari") != -1) return 'Safari';
    if (agt.indexOf("skipstone") != -1) return 'SkipStone';
    if (agt.indexOf("msie") != -1) return 'Internet Explorer';
    if (agt.indexOf("netscape") != -1) return 'Netscape';
    if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
    if (agt.indexOf('\/') != -1) {
        if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
            return navigator.userAgent.substr(0,agt.indexOf('\/'));
        } else {
            return 'Netscape';
        }
    } else if (agt.indexOf(' ') != -1) {
        return navigator.userAgent.substr(0,agt.indexOf(' '));
    } else {
        return navigator.userAgent;
    }
} 

function changeButtonView(){
	if(document.getElementById("photo-change")!=null){
		document.getElementById("photo-change").className='changepic-active';
	}
	if(document.getElementById("photo-submit")!=null){
		document.getElementById("photo-submit").className='upload-active';
      }

}

function showMin_window() {
	var browserType = whichBrowser();
	if(browserType!=null && browserType=='Internet Explorer'){
		if (typeof document.body.style.maxHeight != "undefined") {
  			// IE 7, mozilla, safari, opera 9
		} else {
  			$("body","html").css({height: "100%", width: "100%"});
			$("select","html").css({visibility: "hidden"});
			$("html").css("overflow","hidden");
		}
	}
	errorpageurl= getErrorUrl();
	var errorbox = document.getElementById('errorbox');
	errorbox.innerHTML = "<iframe id='errorFrame' src='"+errorpageurl+"' frameborder='0' class='error-pg'></iframe>";
	document.getElementById('errorbox').className='show'; 
	document.getElementById('lightbox').className='lightbox show'; 
	document.getElementById('errorFrame').className='error-pg show';
}
	

function validateFormFields(){
	
	if(CheckFormValues()){
		if(document.getElementById("groupfrm")!=null){
			document.getElementById("groupfrm").submit();
		}
		return true
	}else{
	
		showMin_window();
	}
}

function validateEditForms(){
	 if(CheckFormValues()){
		 UpdateEditGroup();
		
		 return true
	 }else{
		 showMin_window();
		 return false;
	 }
}
function photo_submit() {
	assingvar="";
  if (document.getElementById("filename").value.length == 0) {
		
			assignerror ="choosefile";
			showMin_window();
			 return false;
	
			} else {
				var sFileName = document.getElementById("filename").value;
				sFileName = sFileName.toLowerCase();
				//alert(sFileName);
				if (stringEndsWith(sFileName, ".jpg") || stringEndsWith(sFileName, ".jpeg") || stringEndsWith(sFileName, ".gif") || stringEndsWith(sFileName, ".png")) {
					document.getElementById("cameo_logo").submit();
					} else {
						assignerror = "invalid Format";
						showMin_window();
						return false;
					}
				}
 
}
function trim(str) {
  		return str.replace(/^\s+|\s+$/g, '');
	}

function CheckFormValues(){
 assignerror="";
 assingvar ="";
 errors;
 isDelete="";
if(document.getElementById("grpname").value == null || document.getElementById("grpname").value.length==0){
	assignerror='Please enter a name for your group';
	
	//alert("please enter a name for your group");
	document.getElementById("grpname").focus();
	return false;
}
else if(document.getElementById("grpname").value!=null  && document.getElementById("grpname").value.length<5){
	assignerror='Please enter a minimum of 5 characters in the group name';
	//alert("Please enter a minimum of 5 characters in the group name");
	document.getElementById("grpname").focus();
	return false;
}
if(checkMetaCharacter(document.getElementById("grpname").value)){
	assignerror='Please make sure to use alphanumeric characters (a-z, 0-9) only in room name';
	//alert("Please make sure to use alphanumeric characters (a-z, 0-9) only");
	document.getElementById("grpname").focus();
	return false;
}
/*if(checkMetaCharacter(document.getElementById("welcomemsg").value)){
	assignerror='Please make sure to use alphanumeric characters (a-z, 0-9) only';
	document.getElementById("welcomemsg").focus();
	return false
}*/
if(document.getElementById("language_code").options!=null && isInvalidGroupName(document.getElementById("grpname").value,document.getElementById("language_code").options[document.getElementById("language_code").selectedIndex].value)){
		document.getElementById("grpname").focus();
		return false;
	}
if (document.getElementById("category_cd").options!=null && document.getElementById("category_cd").options[document.getElementById("category_cd").selectedIndex].value == 0){
	  assignerror='Please select a  category.';
	 //alert("Please select a  Category.");
	document.getElementById("category_cd").focus();
	return false;
}
if(document.getElementById("subcategory_cd").options[document.getElementById("subcategory_cd").selectedIndex].value==0){
	assignerror='Please select a subcategory.';
	//alert("Please select a subcategory");
	document.getElementById("subcategory_cd").focus();
return false;
}
if(document.getElementById("desc")==null || document.getElementById("desc").value.length==0){
	assignerror = "Please enter the room description";
	return false;

}
/*if(checkMetaCharacter(document.getElementById("desc").value)){
	assignerror='Please make sure to use alphanumeric characters (a-z, 0-9) only in room description';
	document.getElementById("desc").focus();
	return false;
}*/
if(document.getElementById("language_code").options!=null && document.getElementById("language_code").options[document.getElementById("language_code").selectedIndex].value==0){
	assignerror='Please select a language';
	//alert("Please select a language");
	document.getElementById("language_code").focus();
	return false;
}
if(document.getElementById("rating").options!=null && document.getElementById("rating").options[document.getElementById("rating").selectedIndex].value == '' ){
	assignerror='Please choose a rating for your group';
	//alert("Please choose a rating for your group"); 
	document.getElementById("rating").focus();
	return false;
}
if(document.getElementById("admin_code")== null || (document.getElementById("admin_code")!=null && document.getElementById("admin_code").value.length==0)){
	assignerror='Please enter admin code for your group';
	document.getElementById("admin_code").focus();
	return false;
}

if(isNaN(document.getElementById("admin_code").value) || parseInt(document.getElementById("admin_code").value)<0 || document.getElementById("admin_code").value.length<4){
	assignerror='Admin code must be a number between 4 or 9 digits';
	return false;
 }
var url=trim(document.getElementById("homepgurl").value);
if(url != "http://" && url !=""){
var tomatch= /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
	if (!tomatch.test(url)){         
		assignerror="Invalid website URL";    
    	return false; 
	}
}
if(validatekeywords()){
	return true
}else{
	return false;
}
return true;
	
}
function checkMetaCharacter(p_val){
						//alert("checkMetaCharacter"+p_val);
						var validchars = "<>@#{}[]+=,;!^()$-";
						var parm1 = p_val.toUpperCase();
						for (var i=0; i<parm1.length; i++) {
						temp = "" + parm1.substring(i, i+1);
						if (validchars.indexOf(temp) >= 0 && temp != " ") {
						//alert("checkMetaCharacter"+p_val+"true");

						return true;
						}
					}
					return false;
				}
function isInvalidGroupName(name, language_code){
					//alert('isInvalidGroupName'+name);
					var spaces = 0;
					if (name == null || trim(name).length==0) {
						assignerror='Room Name cannot be empty';
						//alert("Room Name cannot be empty");
						return true;
					}

					var c = name.toLowerCase().split("");//we lowercase this so that xxx and xXx are equal in the eyes of this routine;
					var ci = 0;

					//next two checks are probalby unnecessary cause they should be checked on the client side
					if (c.length < 5 || c.length > 50){
						assignerror='Room name must be from 5 to 50 characters in length';
						//alert("Room name must be from 5 to 50 characters in length");
						return true;
					}

					//loop thru the char array
					for (var i = 0; i < c.length; i++) {
						ci = c[i];
						//check for a char repeating more then 3 times
						if (i + 3 < c.length){
							if (ci == c[i + 1] && ci == c[i + 2] && ci == c[i + 3]) {
								assignerror='Room name has too many repeating characters at position: ' + i + ' char:'+ ci;
								//alert("Room name has too many repeating characters at position: " + i + " char: " + ci);
								return true;
							}
						}

						//check for 2 spaces next to each other
						if (i + 1 < c.length){
							if (ci == ' ' && c[i+1] == ' ') {
								assignerror='Group name: Consecutive spaces: '+ i + ' char: ' + ci;
								//alert("Group name: Consecutive spaces: " + i + " char: " + ci);
								return true;
							}
						}

						if (i + 6 < c.length) {
							if (ci == ' ' && c[i+2] == ' ' && c[i+4] == ' ' && c[i+6] == ' '){
								assignerror='Group name: Improper use of spaces at position: ' + i;
								//alert("Group name: Improper use of spaces at position: " + i);
								return true;
							}
						}

						//check for 2 char repeating patterns (xyxyxy Samuelson)
						if (i + 5 < c.length) {
							var di = c[i + 1];
							if (ci == c[i + 2] && ci == c[i + 4] &&
								di == c[i + 3] && di == c[i + 5]) {
									assignerror='Group name: Repeating patterns not allowed: ' + i + ' pattern: ' + ci + di;
									//alert("Group name: Repeating patterns not allowed: " + i + " pattern: " + ci + di);
									return true;
								}
						}

						//check for 3 char repeating patterns (abcabcabc George)
						if (i + 8 < c.length) {
							var di = c[i + 1];
							var ei = c[i + 2];
							if (ci == c[i + 3] && ci == c[i + 6] && di == c[i + 4] && di == c[i + 7] &&  ei == c[i + 5] && ei == c[i + 8]){
								assignerror='Group name: Repeating patterns not allowed: ' + i + ' pattern: ' + ci + di + ei;
								//alert("Group name: Repeating patterns not allowed: " + i + " pattern: " + ci + di + ei);
								return true;
							}
						}

						//check for 4 char repeating patterns (abcdabcd Mary)
						if (i + 7 < c.length)  {
							if (ci == c[i + 4] && c[i + 1] == c[i + 5] && c[i + 2] == c[i + 6] && c[i + 3] == c[i + 7]) {
								assignerror='Group name: Repeating patterns not allowed: ' + i + ' pattern: ' + ci + c[i + 1] + c[i + 2] + c[i + 3];
								//alert("Group name: Repeating patterns not allowed: " + i + " pattern: " + ci + c[i + 1] + c[i + 2] + c[i + 3]);
								return true;
							}
						}

						//check for 5 char repeating patterns (abcdeabcde Mary)
						if (i + 9 < c.length) {
								if (ci == c[i + 5] && c[i + 1] == c[i + 6] && c[i + 2] == c[i + 7] && c[i + 3] == c[i + 8] && c[i + 4] == c[i + 9]) {
									assignerror='Group name: Repeating patterns not allowed: ' + i + ' pattern: ' + ci + c[i + 1] + c[i + 2] + c[i + 3] + 	c[i + 4];
								  //alert("Group name: Repeating patterns not allowed: " + i + " pattern: " + ci + c[i + 1] + c[i + 2] + c[i + 3] + 	c[i + 4]);
								  return true;
								}
						}

						//keep track of how many total spaces there are
						if (ci == ' ') spaces++;
						//make sure its a valid char
						/*if (language_code == 21) { //arabic

							var charCd = ci.charCodeAt(0);
							if((charCd >= 192 && charCd <= 255 && charCd != 200) && (group_is_premium==null || trim(group_is_premium).length==0)){
								alert("Arabic chars in room name are allowed only for paid room owners");
								return true;
							}

							if ( (ci >= 'a' && ci <= 'z') || (ci >= 'A' && ci <= 'Z') || (ci >= '0' && ci <= '9') ||
								  (charCd >= 192 && charCd <= 255 && charCd != 200) || (ci == ' '))
								  continue;
							else {
								  alert("Group name: Invalid character found at position: " + (i+1) + " char: " + ci);
								  return true;
							}
						}
						else {
							if ( (ci >= 'a' && ci <= 'z') || (ci >= 'A' && ci <= 'Z') || (ci >= '0' && ci <= '9') || (ci == ' '))
								 continue;
							else {
								alert("Group name: Invalid character found at position: " + (i+1) + " char: " + ci);
								return true;
							}
						}*/
					 } //for

					 //check for too many spaces
					 if (spaces > 7) {
						 assignerror='Group name: Too many spaces';
						//alert("Group name: Too many spaces");
						return true;
					 }

					 //its all good so return null
					 return false;
				}			
function getSubcategory(){
	var code=document.getElementById('category_cd');
	var prefix = code.options[code.selectedIndex].value;
	if(prefix!="0") {
	makeRequest("/g2/SubCatergoryAjax?catg="+prefix);
	}
}
function makeRequest(url){
	if(window.XMLHttpRequest){
		request = new XMLHttpRequest();
	}
	else if(window.ActiveXObject){
		request = new ActiveXObject("MSXML2.XMLHTTP");
	}
	sendRequest(url);
}
function sendRequest(url){
	request.onreadystatechange = onSubCategoryResponse;
	request.open("POST", url, true);
	request.send(null);
}
function onSubCategoryResponse(){
	if(checkReadyState(request)){
		//alert(request.responseXML.xml);
		var subcatgcode=request.responseXML.getElementsByTagName('subcategorycode')[0].firstChild.data;
		var subcatgname=request.responseXML.getElementsByTagName('subcategoryname')[0].firstChild.data;
		var eleSubCatg=document.getElementById('subcategory_cd');
		eleSubCatg.options.length = 0;
		var arrSubCatgCd = subcatgcode.split('|');
		var arrSubCatgName = subcatgname.split('|');
		var i;
		var k;
		k=0;
		for ( i = 0; i < arrSubCatgCd.length; i++ ) {
			if (arrSubCatgCd[i]!="") {
				eleSubCatg.options[k] = new Option(arrSubCatgName[i],arrSubCatgCd[i]);
			 k++;
			}
		}
	}
}
function checkReadyState(obj){
	if(obj.readyState == 4)    {
		if(obj.status == 200){
			return true;
		}
	}
}

function checkEmail(strng) {
	var error = ""
	if(strng==null ||strng == "") {
		return true;
	}
	var emailFilter=/^.+@.+\..{2,3}$/;
	if (!(emailFilter.test(strng))){
		return true;
	}
	
	var illegalChars= /[\(\)\<\>\%\=\,\;\:\\\/\"\[\]]/
	if (!strng.match(illegalChars)) {
		error = "The Email ID contains illegal characters.\n";
	}
	var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._@-";
	var checkStr = strng;
	var passValid = true; var ch;
	for (i = 0;  i < checkStr.length;  i++)	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j)) 
		break;
		if (j == checkOK.length){
			passValid = false;
			break;
		}
	}
	if (passValid){
		return false;
	}else {
		return true;
	}
}

function validatekeywords(){
	var tempstr="";
				var lencount = 0;
				var f =1;
				//tempstr = document.getElementById('tagfield1').value; 
				for(i=1;i<=10;i++){
					var t = 'tagfield'+i;
					if(document.getElementById(t) != null){
					var elem = document.getElementById(t).value;
  					if(elem!=null){
							elem = trim(elem);
						}

					if(elem!=null && elem!="" && elem.length != 0){
						tempstr = tempstr+elem;
						lencount = lencount + 1;
						f =i+1;
						break;
					}
					}
										
				}	
				for(j=f;j<=10;j++){
					var t = 'tagfield'+j;
						if(document.getElementById(t) != null){
						var elem = document.getElementById(t).value;
						
						if(elem!=null){
							elem = trim(elem);
						}
						if(elem!=null && elem!="" && elem.length != 0){
							tempstr = tempstr+","+elem;
							lencount = lencount + 1;
						}
					}
										
				}	

				document.getElementById('keywords').value=tempstr;			
				var wordsplit=document.getElementById('keywords').value;
				lencount= lencount-1;
				if((wordsplit.length - lencount) > 87){
					assignerror = 'You may not enter more than 87 characters.';
					//alert("You may not enter more than 87 characters.");
					return false;
				}
				wordcount=wordsplit.split(",");
				if(document.getElementById('keywords').value!=null && wordcount.length>10){
				assignerror = 'You may not enter more than 10 keywords.';
				//alert("You may not enter more than 10 keywords");
				//document.frmEditGrp.keywords.focus();
				return false;
		}
		
		return true;
}

function getErrorValue(){
	return assignerror;
}

function getGrpExistError(){
	return assingvar;
}
function getServerSideError(){
	return errors;
}

function IsNumeric(input){    
var RE = /^-{0,1}\d*\.{0,1}\d+$/; 
//alert(RE.test(input));
return (RE.test(input));
}


var count = 0;
function addMoreKeyWords(jsSize){

		var pardiv= document.getElementById('groupKeywords')
		if(count<=jsSize){
   			count = jsSize+1;
		}
		
		//var fieldset = document.createElement('fieldset');
		//alert("test");
	
		var str="";
		count=count + 1;

		if(count >10){
			return;
		}
		
		tag = 'tagfield'+count
		var textfield = document.createElement('input');
		textfield.setAttribute('type','text');
		textfield.setAttribute('id',tag); 
		textfield.className='txtbox';
		//str ="<input type ='text' name='' id='"+t+"'/>"
		//fieldset.innerHTML = str;
		//alert(textfield);
		//document.body.appendChild(textfield);
		pardiv.appendChild(textfield);


	}
	
	
	function addMoreTag(jsSize){

		var pardiv= document.getElementById('groupTags')
		if(count<=jsSize){
   			count = jsSize+1;
		}
		
		//var fieldset = document.createElement('fieldset');
		//alert("test");
	
		var str="";
		count=count + 1;

		if(count >10){
			return;
		}
		
		t = 'tagfield'+count
		var textfield = document.createElement('input');
		textfield.setAttribute('type','text');
		textfield.setAttribute('id',t); 
		textfield.className='keywords';
		//str ="<input type ='text' name='' id='"+t+"'/>"
		//fieldset.innerHTML = str;
		//alert(textfield);
		//document.body.appendChild(textfield);
		pardiv.appendChild(textfield);


	}
	

function textCounter(jsmaxcount) {
	var roomdesc=document.getElementById('desc');
	if(roomdesc!=null){
		if (roomdesc.value.length > jsmaxcount){ // if too long...trim it!
			roomdesc.value = roomdesc.value.substring(0, jsmaxcount);
		}
	}
}

function checkForAdult(){
		
		var catg_value = "";
		var subcatg_value="";
		catg_value= document.getElementById("category_cd").options[document.getElementById("category_cd").selectedIndex].value;
		subcatg_value = document.getElementById("subcategory_cd").options[document.getElementById("subcategory_cd").selectedIndex].value;
		
		if (catg_value == 2250 && subcatg_value == 900){ //Early Teens (13-17 ONLY) - NO ADULTS
				$("#ratingdiv").html('<a href="javascript:void(0);" id="grating" relrate="G" onmouseout="UnTip()" onmouseover="Tip(\'This a G rated room intended for a General Audience including minors. Offensive language is not permitted.\')"><img id="gimg" src="/groups/images/g-rating.gif" alt="G" class="active"/></a>');
				$("#rating").val("G");

			}
		else if(catg_value==2900 && subcatg_value==800){
			
				$("#ratingdiv").html('<a href="javascript:void(0);" id="rrating" relrate="R" onmouseout="UnTip()" onmouseover="Tip(\'This is an R-rated room inappropriate for minors. Adult language is permitted, however nudity is not.\')"><img id="rimg" src="/groups/images/r-rating.gif" alt="R" class="active"/></a>');
				$("#rating").val("R");
		}
		else {
				// free group or ultimate
			
				$("#ratingdiv").html('<a href="javascript:void(0);" id="grating" relrate="G" onmouseout="UnTip()" onmouseover="Tip(\'This a G rated room intended for a General Audience including minors. Offensive language is not permitted.\')"><img id="gimg" src="/groups/images/g-rating.gif" alt="G" class="active"/></a><a href="javascript:void(0);" id="rrating" relrate="R" onmouseout="UnTip()" onmouseover="Tip(\'This is an R-rated room inappropriate for minors. Adult language is permitted, however nudity is not.\')"><img id="rimg" src="/groups/images/r-rating.gif" alt="R" /></a>');
				$("#rating").val("G");

			}
			$("#grating,#rrating").click(setRating);
}
function setRating(){
			$("#rimg").removeClass("active");
			$("#gimg").removeClass("active");
			if($(this).attr("relrate") == "R"){
				$("#rimg").addClass("active");
			}
			else if($(this).attr("relrate") == "G"){
				$("#gimg").addClass("active")
			}	
			$("#rating").val($(this).attr("relrate"));
}


$(document).ready(function() {
	$("#grating,#rrating").click(setRating);
	createformSubmit();
});
