$(document).ready(function() {

    var container = $('div.container');
    if ($.validator)
    {
      $.validator.setDefaults({
        onfocusin: false,
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        errorContainer: container,
        errorLabelContainer: $("ol", container),
        wrapper: 'li',
        meta: "validate"
      });
    }

    if ($("#signupForm").length > 0) {
        $("#zipcode").mask("99999");
        $("#areacode").mask("999");
        $("#exchange").mask("999");
        $("#phone").mask("9999");
        $("#ext").mask("9999");

        var validator = $("#signupForm").validate();

        $("#btnCancel").click(function() {
           location.href = 'plans.php';
        });
    }

    if ($("#loginForm").length > 0) {
        var validator = $("#loginForm").validate();
    }

    if ($("#frmSignUpCC").length > 0) {

        $("#cc_zipcode").mask("99999");

        var validator = $("#frmSignUpCC").validate();

        $("#btnCancel").click(function() {
           location.href = 'upgrade_plans.php';
        });
    }

    if ($("#frmForgotPasswordAdvertiser").length > 0) {
        var validator = $("#frmForgotPasswordAdvertiser").validate();
    }

    if ($("#frmMemberSignUp").length > 0) {
        var validator = $("#frmMemberSignUp").validate();
    }

    if ($("#frmSendInvitation").length > 0) {
        $("#divemail2").hide();
        $("#divemail3").hide();
        $("#divemail4").hide();
        $("#divemail5").hide();
        $("#divemail6").hide();
        $("#divemail7").hide();
        $("#divemail8").hide();
        $("#divemail9").hide();
        $("#divemail10").hide();
        var validator = $("#frmSendInvitation").validate();
        $("#btnCancel").click(function() {
           location.href = 'my_affiliate_account.php';
        });
    }

    if ($("#frmAdvertiserEdit").length > 0) {
        var validator = $("#frmAdvertiserEdit").validate();
        $("#zipcode").mask("99999");
        $("#areacode").mask("999");
        $("#exchange").mask("999");
        $("#phone").mask("9999");
        $("#btnCancel").click(function() {
           location.href = 'my_account.php';
        });
    }

    if ($("#frmAdvertiserEdit2").length > 0) {
        var validator2 = $("#frmAdvertiserEdit2").validate();
        $("#cc_zipcode").mask("99999");
        $("#btnCancel").click(function() {
           location.href = 'my_account.php';
        });
    }

    if ($("#frmUgradePlan").length > 0) {
        $("#btnSubmit").click(function() {            
            var checked = false;
            var buttons = document.frmUgradePlan;
            for (var i=0; i<buttons.length; i++)
            {
                if (buttons[i].checked) {
                    checked = true;
                    break;
                }
            }
            if(!checked) {
                alert("Please choose a Plan to proceed.");
            } else {
                if (!window.confirm("Are you sure, you want to upgrade. Your Credit Card will be charged for this upgrade.")) {
                    return false;
                }
            }            
            return checked ; 
        })
    }
    
    if ($("#frmAdvertiserPassword").length > 0) {
        var validator = $("#frmAdvertiserPassword").validate();
        $("#btnCancel").click(function() {
           location.href = 'my_account.php';
        });
    }
})

function isEmail(emailid)
{
	if(emailid.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9_-]+\.+[a-zA-Z0-9._]+$/)) {
		return true;
	} else {
		return false;
    }
}

// function to set focus to the what box on load
function setFocus(){
	document.frmZip.q.focus();
}


//function to check if the what textbox is blank
function checkWhatFld(what, where)
{
	what.value = what.value.replace(/^\s+/, '');
	what.value = what.value.replace(/\s+$/, '');

    if(what.value == "" || what.value == "Please enter the keyword.")
    {
    	what.focus();
    	what.value = "Please enter the keyword.";
    	select_all(what);
    	return false;
    }

    var iChars = "!@#$%^&*()+_=[]\\\';./{}|\":<>?";

    for (var i = 0; i < where.value.length; i++) {
      	if (iChars.indexOf(where.value.charAt(i)) != -1) {
      		where.focus();
      		alert ("Special characters are not allowed in Where.");
      		return false;
      	}
	}
}

function select_all(thisFld)
{
	var Fld_val=eval("thisFld");
	//Fld_val.focus();
	//Fld_val.select();
}

// function to open print pop up
function show_popup(link){
	open(link,'bids', 'width=750,height=620,menubar=yes,status=no,resizable=no,location=no,toolbar=no, personalbar=no,scrollbars=yes');
}

//function to display and hide a section for eg: nearby cities, national chains, tags etc.
var userAgent = navigator.userAgent.toLowerCase();
var MyBrowser =
    {
        Browser:{
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
        safari: /webkit/.test( userAgent ),
        opera: /opera/.test( userAgent ),
        msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
        }
    };

function changeSortOrder(sort_type)
{
    document.cookie = "sort_type="+escape(sort_type);
    var tmp = window.location.href;
    var temp = tmp.split('page_');
    var tmp = temp[0]+'page_1.htm';

    if(MyBrowser.Browser.safari)
    {
        //needed
        tmp = tmp.replace(/:/,"@")
        tmp = escape(tmp);
        tmp = tmp.replace(/@/,":")
    }
    window.location.href=tmp;
}

function showHideSection(section, obj)
{
    var display;
    display = document.getElementById(section).style.display;
    document.getElementById(section).style.display = (display=="") ? "none" : "";
    var nodes = obj.childNodes;
    node = nodes[0];
    var ta=document.createElement("textarea");
    if(display)
        ta.innerHTML = "&#171;&nbsp;close";
    else
        ta.innerHTML = "view all&nbsp;&#187;";
    node.data = ta.value;
    obj.blur();
}

function showMore(id,more_element)
{
    var display;
    hght = document.getElementById(id).style.height;
    document.getElementById(id).style.height = (hght!="auto") ? "auto" : "32px";
    if(hght!="auto")
        more_element.innerHTML = "&#171;&nbsp;close";
    else
        more_element.innerHTML = "view all&nbsp;&#187;";
    more_element.blur();
}

function setHeight(cnt)
{
    for(i=0;i<cnt;i++)
    {
		if(document.getElementById("box"+i))
		{
			document.getElementById("box"+i).style.display = "";
			if(document.getElementById("box"+i).offsetHeight > 35)
			{
				document.getElementById("more"+i).style.display = "";
				document.getElementById("box"+i).style.height = "32px";
			}
		}
    }

}

function goThere(rdurl) {
    location.href=rdurl;
    return false;
}

var allowdTag = new Array("IMG");

function isAllowdTag(node)
{
   for (var i = 0; i < allowdTag.length; i++)
   {
     if (node.tagName == allowdTag[i])
     {
		return true;
     }
   }
   return false;
}

function scanNodeForImages(parent)
{
	var nodes = parent.childNodes;
    for (var i = 0; i < nodes.length; i++)
    {
    	var node = nodes[i];

    	if(!isAllowdTag(node))
    	{
    		continue;
    	}

		if(node.width > 110)
		{
			node.width = 110;
			node.height = ( 110 / node.width ) * node.height;
    	}
		if(node.height > 75)
		{
			node.height  = 75;
			node.width = ( 75 * node.width ) / node.height;
    	}
    }
}

function resizeImage()
{
	var paras = $A(document.getElementsByClassName('thumb-image'));
	paras.each(function show(s){
		scanNodeForImages(s);
	});
}

function setPopularCity(city, domain)
{
	document.cookie = "where="+escape(city)
                         + ";path=/;domain=.UnitedYellow."+domain+";";
}

function debug(str, color)
{
	var div = document.createElement("div");
	var br = document.createElement("br");
	var txt = document.createTextNode(str);
	div.appendChild(txt);
	div.appendChild(br);
	document.body.appendChild(div);
	if(typeof color!=undefined)
	{
	  div.style.color = color;
	}
}

function searchJobs(domain, location_path){
	strKeyword = document.form1.jobfield.value.toLowerCase();
	strKeyword = escape(escape(strKeyword));
	strKeyword = strKeyword.replace(new RegExp(/\+/g), '%252b');
	strKeyword = strKeyword.replace(new RegExp(/\//g), '%252f');

	url = 'http://jobs.zipcodez.' + domain + location_path + 'job/' + strKeyword + '.htm';

	open(url, 'bids', '');
}


//function to check if the what textbox is blank
function checkJobFld(what, domain, location_path)
{
	what.value = what.value.replace(/^\s+/, '');
	what.value = what.value.replace(/\s+$/, '');

    if(what.value == "" || what.value == "Please enter the keyword.")
    {
    	what.focus();
    	what.value = "Please enter the keyword.";
    	select_all(what);
    	return false;
    }
    searchJobs(domain, location_path);
    return false;
}

function getImageResult() {
	var d = new Date();
	var url_captcha = "../lib/captcha/reload_captcha.php?t="+d.getTime();
	var NewImage = $.ajax({url: url_captcha,async: false}).responseText;
	document.getElementById("dyimage").src = "../lib/captcha/create_img.php?IMGVER_RandomText="+NewImage;
	document.getElementById("imc").value = NewImage;
}

function bookmarkListing(title, url, listingid)
{
	var message = $.ajax({url: 'user/bookmark_listing.php?title='+title+'&url='+url+'&listing_id='+listingid,async: false}).responseText;
	if (message == 'ok') {
		alert('Listing is successfully added to your account.');
	} else {
		alert('Listing is allready added.');
	}
}

function update_click(id, searchid, click_id, adv_pid, recordtype) {
  send_click_request(searchid, click_id, adv_pid, recordtype);
  var businessname = $('#businessname'+adv_pid).length ? $('#businessname'+adv_pid).html() : '';
  var addressline_1 = $('#addressline_1'+adv_pid).length ? $('#addressline_1'+adv_pid).html() : '';
  var addressline_2 = $('#addressline_2'+adv_pid).length ? $('#addressline_2'+adv_pid).html() : '';
  var telephone = $('#phone'+adv_pid+'_data').length ? $('#phone'+adv_pid+'_data').html() : '';
  var url = $('#url'+adv_pid).attr('href');
  switch(click_id) {
    case 1:
      window.open($('#'+id+adv_pid).attr('title'));
      break;
    case 3:
      getSendToEmail(adv_pid, businessname, addressline_1, addressline_2, telephone, url);
      break;
    case 4:
      getSendToMobile(adv_pid, businessname, addressline_1, addressline_2, telephone);
      break;
    case 5:
      $('#'+id+adv_pid).hide();
      $('#'+id+adv_pid+'_data').show();
      break;
    default:
      break;
  }
}

function send_click_request(searchid, click_id, adv_pid, recordtype) {
  if (recordtype == 1) {
    $.get('clicks.php', { 'searchid': searchid, 'click_id': click_id, 'adv_pid': adv_pid, 'recordtype': recordtype } );
  }
}

var sendToEmail = function (data, textStatus)
{
    $("#dialogbox").html(data);
    $('#dialog_message').html('');
    $('#from_name').val('');
    $('#from_email').val('');
    $('#to_email').val('');
    $("#dialogbox").dialog({
        width: 500,
        closeText: ''
    });
    $("#dialogbox").dialog('open');
    $('#btnCancel').click(function() {
         $("#dialogbox").dialog('close');
    });
    $('#btnSend').click(function() {
        
        var fromname  = $('#from_name').val();
        var fromemail = $('#from_email').val();
        var toemail   = $('#to_email').val();
        var oEditor = FCKeditorAPI.GetInstance('email_body') ;
        var emailbody = oEditor.GetXHTML();        
        //var emailbody = $('#email_body').val();
        var subject   = $('#subject').val();
        var type      = $('#type').val();
        var pid      = $('#pid').val();
        if ($.trim(fromname) == '') {
            alert('Please enter from name.');
            return false;
        }
        if ($.trim(fromemail) == '') {
            alert('Please enter from email.');
            return false;
        }
        if ($.trim(toemail) == '') {
            alert('Please enter to email.');
            return false;
        }
        if ($.trim(subject) == '') {
            alert('Please enter Subject.');
            return false;
        }
        if ($.trim(emailbody) == '') {
            alert('Please enter email body.');
            return false;
        }
        var message = $.ajax({url: '/sendmail.php?fromname='+fromname+'&fromemail='+fromemail+'&toemail='+toemail+'&emailbody='+emailbody+'&subject='+subject+'&type='+type+'&pid='+pid,async: false}).responseText;

        $('#dialog_message').html(message);
        $('#from_name').val('');
        $('#from_email').val('');
        $('#to_email').val('');
    })
}

function getSendToEmail(adv_pid, businessname, addressline_1, addressline_2, telephone, url)
{
  $.get(
    'send_to_mail.php', 
    {
      'adv_pid':adv_pid,
      'businessname':businessname,
      'addressline_1':addressline_1, 
      'addressline_2':addressline_2, 
      'telephone':telephone, 
      'url':url
    },
    sendToEmail
  );
}

var sendToMobile = function (data, textStatus)
{
    $("#dialogMobile").html(data);
    $('#m_dialog_message').html('');
    $("#dialogMobile").dialog({
        width: 500,
        closeText: ''
    });
    $("#dialogMobile").dialog('open');
    $("#btnSendMobile").bind('click',function() {
        var fromname       = $('#m_from_name').val();
        var fromemail      = $('#m_from_email').val();
        var tophone        = $('#m_to_phone').val();
        var emailbody      = $('#m_email_body').val();
        var subject        = $('#m_subject').val();
        var type           = $('#m_type').val();
        var pid            = $('#m_pid').val();
        var sel_mobile_srp = $('#sel_mobile_srp').val();

        if ($.trim(fromname) == '') {
            alert('Please enter from name.');
            return false;
        }
        else if ($.trim(fromemail) == '') {
            alert('Please enter from email.');
            return false;
        }
        else if ($.trim(tophone) == '') {
            alert('Please enter mobile number.');
            return false;
        } else {
            var message = $.ajax({url: '/sendmail.php?fromname='+fromname+'&fromemail='+fromemail+'&tophone='+tophone+'&emailbody='+emailbody+'&subject='+subject+'&type='+type+'&pid='+pid+'&sel_mobile_srp='+sel_mobile_srp,async: false}).responseText;
            $('#m_dialog_message').html(message);
            $('#m_from_name').val('');
            $('#m_from_email').val('');
            $('#m_to_phone').val('');
        }        
        
    });
    $("#btnCancelMobile").click(function() {
        $("#btnSendMobile").unbind('click');
        $("#dialogMobile").dialog('close');
    });

}

function getSendToMobile(adv_pid, businessname, addressline_1, addressline_2, telephone)
{
  $.get(
    'send_to_mobile.php', 
    {
      'adv_pid':adv_pid,
      'businessname':businessname,
      'addressline_1':addressline_1, 
      'addressline_2':addressline_2, 
      'telephone':telephone 
    },
    sendToMobile
  );
}

function show_keywords() {
	var keywords = $('#othertags').val();
	var keyword_url = 'category_keywords.php?&catid1='+catid1+'&catid2='+catid2+'&catid3='+catid3+'&keywords='+encodeURIComponent(keywords)+'&height=200&width=700'; 
	tb_show('Select Keywords', keyword_url, false);
}

function hide_keywords() {
	var arr = new Array();
	var i = 0;
	$('#keyword_table').find('input[type="checkbox"]').each(function () {
		if ($(this).is(':checked'))
		{
			arr[i] = $(this).val();
			i++;
		}
	});
	var keywords = arr.join(', ');
	$('#othertags').val(keywords);
	$('#othertagsStatic').html(keywords);
	
	if (keywords != '')
	{
		$('#othertags_div').show();
	}
	else {
		$('#othertags_div').hide();
	}
	tb_remove();
}

function show_catselector(cat) {
	if (cat < 2){var title="Primary";}
	else if (cat > 2){var title="Other";}
	else {var title="Secondary";}
        var cat_url = 'category_selector.php?&catid='+cat+'&height=200&width=700&inlineId=cats';
        tb_show('View All Categories ', cat_url, true);
}

function hide_catselector1(catval) {
	//form.addlistingForm.cat1.value=catval;
        tb_remove();
}

function hide_catselector2(catval) {
        //form.addlistingForm.cat2.value=catval;
        tb_remove();
}

function hide_catselector3(catval) {
        //form.addlistingForm.cat3.value=catval;
        tb_remove();
}

function validateFrmTerms()
{
    var name = $('#aff_uname').val();
    name = $.trim(name);
    if (name.length == 0) {
        alert("Please enter desired affiliate name");
        return false;
    }
    return true;
    
}

function enableDisableBox()
{
    //if ($(this).is(':checked'))
    if ($('#cc_pri_address').is(':checked')) {
        $('#cc_bill_address').attr("disabled","disabled");
        $('#cc_city').attr("disabled","disabled");
        $('#cc_state').attr("disabled","disabled");
        $('#cc_zipcode').attr("disabled","disabled");
    } else {
        $('#cc_bill_address').removeAttr("disabled");
        $('#cc_city').removeAttr("disabled");
        $('#cc_state').removeAttr("disabled");
        $('#cc_zipcode').removeAttr("disabled");
    }
}

function showbookmarks() {
	if ($('#social').is(':hidden'))
	{
		$('#social').show();
	}
	else {
		$('#social').hide();
	}
}

function upgradeplan(planid) {
	if (!window.confirm("Are you sure, you want to upgrade. Your Credit Card will be charged for this upgrade.")) {
        return false;
    } else {
    	var message = $.ajax({url: 'upgrade_plan_submit.php?planid='+planid,async: false}).responseText;;
    	if (message == 'ok') {
    		var msg = "Please add credit card info to upgrade";
    		window.location.href="adv_signup_cc.php?message="+msg;
    	} else {
    		window.location.href="adv_signup_cc.php";	
    	}
    }
}

function categoryCheck(id)
{
	catname = $('#'+id).val();
	$.ajax({
        url: '/ajax.php?catname='+catname+'&cmd=categorycheck',
        async: false,
        success: function(responseText) {
        	if(responseText != 'OK') {
        		alert('Category does not exsist. Please select different Category.');
				$('#'+id).val('');
				$('#'+id).focus();
			}
        }
    });
}

function checkPromocode(id,planid,parentplan,action)
{
	code = $('#'+id).val();
	var data = $.ajax({
		url: '/ajax.php?promocode='+code+'&planid='+planid+'&parentplan='+parentplan+'&action='+action+'&cmd=promocheck',
		async: false
		}).responseText;
	if(data != 'OK') {
   		$('#promoMessage').html(data);
   		$('#promoMessage').show();
   	} else {
   		$('#promoMessage').html('');
   		$('#promoMessage').hide();
   		window.location.reload();
   	}
}

function removePromotion()
{
	var planid = $("input[@name='selectedplan']:checked").val();	
	$.ajax({
		url: '/ajax.php?planid='+planid+'&cmd=removePromo',
		async: false
		})
	   	window.location.reload();
}

function displayAd(sectionid,what)
{
	var data = $.ajax({
		url: '/ajax.php?sectionid='+sectionid+'&what='+what+'&cmd=displayad',
		async: false
		}).responseText;
	if(data != '') {
   		$('#adblock').html(data);
   	} 
}

