//toggle filter checkboxes
function toggleCB(box_id)
{
	var cb = document.getElementById(box_id);
	
	if(cb.checked == true)
	{
		cb.checked = false;
	}
	else
	{
		cb.checked = true;
	}
	
}

function toggleAllCB(id)
{
	var ele = document.getElementById(id);
	var mode = null;	
	
	if(ele.checked == false)
		mode = false;
	else if(ele.checked == true)
		mode = true;
	
	
	var inputArr = document.getElementsByTagName('input');
	if(inputArr != '')
	{	
		for(i=0; i<inputArr.length; i++)
		{
			if(inputArr[i].type == 'checkbox')
			{
				inputArr[i].checked= mode;				
			}
		}
	}
}

function toggleDIV(divID, force)
{
	var divEle=document.getElementById(divID);
	
	if(force != '' && force != null)
	{
		if(force == 'expand')		
			divEle.style.display='block';
		else if(force == 'collape')
			divEle.style.display='none';
	}
	else
	{
		if(divEle.style.display=='block')
		{
			divEle.style.display='none';
		}
		else
		{
			divEle.style.display='block';
		}
	}
}

function phoneCapa_changeSign()
{
	var phoneCapaSecDiv = document.getElementById('phoneCapaSecDivID');
	var phoneCapaSecClpsTd = document.getElementById('phoneCapaSecClpsTdID');
	
	if(phoneCapaSecDiv.style.display == 'block')
	{
		phoneCapaSecClpsTd.innerHTML = '- Sections';		
	}
	else
	{
		phoneCapaSecClpsTd.innerHTML = '+ Sections';		
	}	
}

function phoneCapa_handleModelTF()
{
	document.getElementById("phoneCapaModelTfId").className = 'phoneCapaTxtINPUT';
	document.getElementById("phoneCapaModelTfId").focus();
	document.getElementById("sel_mode").value='model';
	
	document.getElementById("phoneCapaUaTfId").className = 'phoneCapaTxtINPUTDesel';
	
}

function phoneCapa_handleUaTF()
{
	document.getElementById("phoneCapaModelTfId").className = 'phoneCapaTxtINPUTDesel';
	
	document.getElementById("phoneCapaUaTfId").className = 'phoneCapaTxtINPUT';
	document.getElementById("phoneCapaUaTfId").focus();
	document.getElementById("sel_mode").value='ua';
}

function handleEnter(e)
{
	if(!e) e=window.event;
 	var key = e.keyCode ? e.keyCode : e.which;
	
	if(key == 13)
	{
		phoneCapa_searchUaAjax();
		return;
	}
}

function phoneCapa_searchUaAjax()
{
	//get ajax request
	var ajaxRequest = CreateAjaxRequest();
	if(ajaxRequest == null) return false;
	
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{		
		if(ajaxRequest.readyState == 4)
		{			
			//hide loader
			document.getElementById("phoneCapaResDivId").innerHTML = '';
			
			if(ajaxRequest.responseText)
			{
				var jsonData = eval('(' + ajaxRequest.responseText + ')');
				var uaArr_len = 0;
				
				if(jsonData.ua_arr != null)
					uaArr_len = jsonData.ua_arr.length;
				
				var msg ='';				
				var sel_mode_txt = '';
				var res_str = '';
				
				if(jsonData.err == '' || jsonData.err == null)
				{
					if(jsonData.sel_mode == 'model')
					{
						sel_mode_txt = "Brand/Model"; 
					}
					else if(jsonData.sel_mode == 'ua')
					{
						sel_mode_txt = "User Agent"; 
					}
					
					
					if(uaArr_len >= 80)
					{
						msg = "Search Results for "+sel_mode_txt+": '"+jsonData.search_key+"' (Showing relavant 80 Phones)"; 
					}
					else
					{
						msg = "Search Results for "+sel_mode_txt+": '"+jsonData.search_key+"'";
						
						if(uaArr_len == 1)
						{
							msg += " (1 Phone found)";
						}
						else if(uaArr_len > 1)
						{
							msg += " ("+uaArr_len+" Phones found)";
						}
						
					}
					
					//get main result holder
					var phoneCapaResDiv = document.getElementById("phoneCapaResDivId");
					
					//show section
					if(jsonData.ua_arr != null)
					{
						toggleDIV('phoneCapaSecDivID', 'expand');
						phoneCapa_changeSign();
					}
					
					//add space and res msg				
					res_str += '<div id="phoneCapaResTitleDivId" class="phoneCapaResTitleDIV">'+msg+'</div>';
					
					//if no results
					if(jsonData.ua_arr == null)
					{
						res_str += '<div class="phoneCapaResUaLabelDIV" align="center">No devices Mathced you query</div>';
						phoneCapaResDiv.innerHTML=res_str;
						return;
					}
					
					//add main blocks
					for(i=0; i<uaArr_len; i++)
					{
						var  phone_img = jsonData.ua_arr[i].phone_img;
						var  user_agent = jsonData.ua_arr[i].user_agent;
						var  brand = jsonData.ua_arr[i].brand;
						var  model = jsonData.ua_arr[i].model;						
						//var  deviceID = jsonData.ua_arr[i].deviceID;
						
						res_str += '<div class="phoneCapaResBlockDIV">';
						res_str += '	<div class="phoneCapaResImgDIV"><a class="phoneCapaResLinkA" href="javascript:phoneCapa_showPhnData(\''+escape(user_agent)+'\');" target="_self"><img class="phoneCapaResImg" src="'+phone_img+'" width="72" height="72" border="0" onmouseover="this.style.borderColor=\'#D9D4C6\';" onmouseout="this.style.borderColor=\'#EFEBE5\';" /></a></div>';
						res_str += '	<div class="phoneCapaResUaLabelDIV"><b>Brand:</b> '+brand+'<br /><b>Model:</b> '+model+'<br /> <b>User Agent:</b></div>';
						res_str += '	<div class="phoneCapaResUaDIV"><a class="phoneCapaResLinkA" href="javascript:phoneCapa_showPhnData(\''+user_agent+'\');" target="_self">'+user_agent+'</a></div>';
						res_str += '</div>';
					}
					
					phoneCapaResDiv.innerHTML=res_str;
				}
				else
				{
					reportMsgBox(jsonData.err);
				}
			}
			else
			{
				reportMsgBox("Error: Invalid Data");
			}
		}
		else
		{
			//show loader
			//document.getElementById("phoneCapaResDivId").innerHTML = '<img class="phoneCapaLoadingIMG" src="image/templateImg/gallery_loader.gif" border="0" />';				
		}
	}
	
	/*Get element value & set it as paramiter*/	
	var phone_key = document.getElementById("phoneCapaModelTfId").value;
	var ua_key = document.getElementById("phoneCapaUaTfId").value;
	var sel_mode = document.getElementById("sel_mode").value;
	
	if((sel_mode == 'model' && phone_key != '') || (sel_mode == 'ua' && ua_key != ''))
	{
		//show div + loader		
		document.getElementById("phoneCapaResDivId").style.display = 'block';
		document.getElementById("phoneCapaResDivId").innerHTML = '<img class="phoneCapaLoadingIMG" src="image/templateImg/gallery_loader.gif" border="0" />';
		
		//now set parameter	
		//var queryString = "?phone_key="+phone_key+"&ua_key="+ua_key+"&sel_mode="+sel_mode+"&dummy=" + new Date().getTime();
		//var queryString = "_phone_key_"+phone_key+"_ua_key_"+ua_key+"_sel_mode_"+sel_mode+"_dummy_"+new Date().getTime()+".html";		
		var queryString = "phone_key="+phone_key+"&ua_key="+ua_key+"&sel_mode="+sel_mode+"&dummy=" + new Date().getTime(); //POST
		
		ajaxRequest.open("POST", "phoneCapaSearchUaAjax.html", true);
		ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxRequest.setRequestHeader("Content-length", queryString.length);
		ajaxRequest.setRequestHeader("Connection", "close");	
		ajaxRequest.send(queryString);
	}
	else
	{
		reportMsgBox("Please Select & Fill in the <b>Brand/Model</b> or the <b>User Agent</b> field.");
	}
}


function phoneCapa_showPhnData(ua)
{
	
	var phoneCapaSecCbTD = document.getElementById("phoneCapaSecCbTdId");
	var cbArr = phoneCapaSecCbTD.getElementsByTagName('input');
	
	var url = host + "phone_capa_details_ua_"+strip_tags(ua)+"_section_";
	var empty = true;
	
	for(i=0; i<cbArr.length; i++)
	{
		if(cbArr[i].type == 'checkbox')	
		{
			if(cbArr[i].id != 'all' && cbArr[i].checked == true)	
			{
				//empty check
				empty = false;
				url += cbArr[i].value+"|";							
			}
		}
	}
	
	url += '.html';
	
	if(empty == false)
	{
		//url = url.substr(0, url.length-1);		
		url = url.substr(0, url.length);
		phoneCapa_showCaptcha(url, ua);		
	}
	else
	{
		reportMsgBox("You must at least select <b>One Section</b>.");
	}
	
}

function phoneCapa_makeCaptchaDiag(url, ua)
{
	var content = '<div style=\'width:400px; height:100%; display:table; background:#fff; border:solid 0px #c1b49a;\'>';
	content	+= '<div class=\'homeTipTitleDIV\' style=\'background:#BF3802;\'>Are you Human ?</div>';
	content	+= '<div style=\'float:left;\'>';
	content	+= '<table border=\'0\' cellpadding=\'0\' cellspacing=\'0\' style=\'border:solid 0px #bbaf96;\'>';
	content	+= '<tr>';
	content	+= '	<td class=\'newsDetailHolderTD\'>';
	content	+= '		<div class=\'newsDetailDateDIV\'><b>User Agent:</b> <span class=\'newsDetailDateSPAN\'>'+ua+'</span></div>';
	content	+= '	</td>';
	content	+= '</tr>';
	
	content	+= '<tr>';
	content	+= '	<td class=\'newsDetailBodyTD\'>';
	content	+= '	<div id="phoneCapaCaptchaHolderId" style=\'height:80px; overflow:auto;\'>';
	content	+= '         <div id="phoneCapaCaptchaMsgId" class="phoneCapaCaptchaMsgDIV"><!-- err msg --></div>';
	content	+= '		 <div style="float:left; padding-left:25px;">Type what you see : <input class="phoneCapaCaptchaTF" type="text" name="phoneCapaCaptcha" id="phoneCapaCaptchaId" onkeypress="handleCaptchaEnter(event);" /></div> <div style="float:left;padding-left:5px;"><img id="phoneCapaCaptchaImgId" src="captcha/CaptchaSecurityImages.php?width=90&height=30&characters=5&dummy="'+new Date().getTime()+' /></div> <div style="float:left;padding-left:5px;"><img class="phoneCapaCaptchaRefIMG" src="image/templateImg/phoneCapaCaptchaRef.png" title="Refresh Captcha" alt="Refresh" onclick="phoneCapa_refCaptcha();" /></div>';
	content	+= '         <div class="phoneCapaNwDIV" align="left"><input type="checkbox" id="new_window" name="new_window" value="1" />&nbsp;Open in a new window</div>';
	content	+= '         <div class="phoneCapaCaptchaNoteDIV">*This verification is to prevent bots from hammering our servers.</div>';
	content	+= '		 <input type="hidden" id="phoneCapaDetailUrlId" name="phoneCapaDetailURL" value="'+url+'" />';
	content	+= '	</div>';
	content	+= '	</td>';
	content	+= '</tr>';
	
	content	+= '<tr>';
	content	+= '	<td class=\'newsDetailHolderTD\'>';	
	content	+= '		<div style=\'float:right;padding:1px; background:#fff;border:solid 1px #bf3802;\'><input class=\'homeTipNewsBtn\' type=\'button\' name=\'closePhoneCapaCaptchaDiag\' value=\'Close\' onClick=\'tt_HideInit();hideModalBG();\' onmouseover=\"this.className=\'homeTipNewsBtnHover\';\" onmouseout=\"this.className=\'homeTipNewsBtn\';\" ></div>';
	content	+= '		<div style=\'float:right;padding:1px;width:3px; background:#fff;\'><!-- --></div>';
	content	+= '		<div style=\'float:right;padding:1px; background:#fff;border:solid 1px #bf3802;\'><input class=\'homeTipNewsBtn\' type=\'button\' name=\'submitPhoneCapaCaptchaDiag\' value=\'  OK  \' onClick=\'phoneCapa_submitCaptchaAjax();\' onmouseover=\"this.className=\'homeTipNewsBtnHover\';\" onmouseout=\"this.className=\'homeTipNewsBtn\';\" ></div>';
	content	+= '		<div style=\'float:right;background:#fff;\'>&nbsp;</div>';
	content	+= '		<div id="phoneCapaCaptchaLoadingId" style=\'display:none;float:right;padding:1px;width:18px;padding-top:3px; background:#fff;\'><img src="image/templateImg/phoneCapaCaptchaLoading.gif" /></div>';
	content	+= '	</td>';
	content	+= '</tr>';
	content	+= '</table>';
	content	+= '</div>';
	content	+= '</div>';		
		
	return content;	
}


function phoneCapa_showCaptcha(url, ua)
{
	showModalBG();
	
	Tip(phoneCapa_makeCaptchaDiag(url, ua), EXCLUSIVE, true, STICKY, true, CLICKCLOSE, false, CENTERWINDOW, true, CENTERALWAYS, true, BGCOLOR, '#FFFFFF', BORDERWIDTH, 2, BORDERCOLOR, '#bf3802', WIDTH, 404, DELAY, 20, FADEIN, 0, FADEOUT, 0, COPYCONTENT, false, CENTERMOUSE, false, OFFSETY, 20);
	
	//refresh captcha to get a new captcha
	phoneCapa_refCaptcha();
	
	//set focus on captcha field // doesnt work for some reason
	//document.getElementById("phoneCapaCaptchaId").focus()
}


function phoneCapa_refCaptcha()
{
	var captcha = document.getElementById("phoneCapaCaptchaImgId")
	captcha.src = captcha.src + '&dummy=' + (new Date()).getTime();
}

function handleCaptchaEnter(e)
{
	if(!e) e=window.event;
 	var key = e.keyCode ? e.keyCode : e.which;
	
	if(key == 13)
	{
		phoneCapa_submitCaptchaAjax();
		return;
	}
}

function phoneCapa_submitCaptchaAjax()
{
	var captchaText = document.getElementById("phoneCapaCaptchaId").value;
	var url = document.getElementById("phoneCapaDetailUrlId").value;
	
	
	//get ajax request
	var ajaxRequest = CreateAjaxRequest();
	if(ajaxRequest == null) return false;
	
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{		
		if(ajaxRequest.readyState == 4)
		{			
			//hide captcha loader
			document.getElementById("phoneCapaCaptchaLoadingId").style.display = 'none';
			
			if(ajaxRequest.responseText)
			{	
				var jsonData = eval('(' + ajaxRequest.responseText + ')');
				
				if(jsonData != null && jsonData != '')
				{
					if(jsonData.captcha_stat == 'ok')
					{							
						//alert(document.getElementById("new_window").checked);
						if(document.getElementById("new_window").checked == true)
						{
							window.open(url, '_new');
						}
						else
						{
							window.open(url, '_self');
						}
					}
					else if(jsonData.captcha_stat == 'error')
					{
						phoneCapa_showCaptchaMsg("Incorrect Captcha, please retype.");
					}
				}
				else
				{
					phoneCapa_showCaptchaMsg("Error: please retry.");
				}
			}
			else
			{
				phoneCapa_showCaptchaMsg("Error: please retry.");
			}
				
		}
		else
		{
			//keep showing loader
		}
	}	
	
	//send request
	if(captchaText != '')
	{
		//show captcha loader		
		document.getElementById("phoneCapaCaptchaLoadingId").style.display = 'block';
		
		//now set parameter	
		//var queryString = "?captchaText="+captchaText+"&dummy="+new Date().getTime();
		var queryString = "_captchaText_"+captchaText+"_dummy_"+new Date().getTime()+".html";
		
		ajaxRequest.open("GET", "phoneCapaVerifyCaptchaAjax"+queryString, true);
		ajaxRequest.send(null);		
	}
	else
	{
		//cant use diag over diag
		phoneCapa_showCaptchaMsg("Please type in the letters in the <b>Captcha Image</b>");		
	}
	
}

function phoneCapa_showCaptchaMsg(msg)
{
	var phoneCapaCaptchaHolderDIV = document.getElementById("phoneCapaCaptchaHolderId");
	phoneCapaCaptchaHolderDIV.style.height = "120px";
	
	var phoneCapaCaptchaMsgDIV = document.getElementById("phoneCapaCaptchaMsgId");
	phoneCapaCaptchaMsgDIV.innerHTML = msg;
	phoneCapaCaptchaMsgDIV.style.display='block';
	
	document.getElementById("phoneCapaCaptchaId").focus();
}

function strip_tags(str, allowed_tags) {
    var key = '', tag = '', allowed = false;
    var matches = allowed_array = [];
 
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
  
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
 
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
 
    return str;
}
