

function MS_swap(Mitem,Mtype){
  Mitem.src=Mitem.getAttribute(Mtype || "origsrc");
}

function MS(img_swap){
	img_swap.setAttribute("onload","");
	img_swap.setAttribute("origsrc",img_swap.src);
	img_swap.oversrc_img = new Image();
  	img_swap.oversrc_img.src=img_swap.getAttribute("oversrc");
    img_swap.onmouseover = new Function("MS_swap(this,'oversrc');");
    img_swap.onmouseout = new Function("MS_swap(this);");
	img_swap.style.cursor = 'pointer';
}

function M_object(obj){
		if (document.getElementById)
			return document.getElementById(obj)
		else if (document.all)
			return document.all[obj]
}

function setCookie(name, value, days) {
    var expires = '';
    
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    
    value = escape(value);

    document.cookie = name + "=" + value + expires + "; path=/"
}

var typeStr = 'Type in a keyword or your competitor\'s domain'; 

function getCookie(name) {
      var prefix = name + "=";
      var cookieStartIndex = document.cookie.indexOf(prefix);
      if (cookieStartIndex == -1) return null;
      var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
      if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
      return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

// onfocus
function inputClearTxt() {
    var sinput = document.getElementById('searchText');
    if (sinput && sinput.className != 'blackfont') {
        sinput.value = "";
        sinput.className = "blackfont";
    }
}

// onblur
function inputResetTxt() {
    var sinput = document.getElementById('searchText');
    if (sinput && sinput.value == '' && sinput.className != 'greyfont') {
        sinput.value = typeStr;
        sinput.className = "greyfont";
    }
    else {
        setCookie("txt_search", sinput.value);
    }
}

function stopEvent(ev) {
    ev = ev.browserEvent || ev;
                        
    if(ev.preventDefault) {
        ev.preventDefault();
    } else {
        ev.returnValue = false;
    }
}

function trimLeft(str) {
  return str.replace(/^\s+/, '');
}

function trimRight(str) {
  return str.replace(/\s+$/, '');
}

function trimBoth(str) {
  return trimRight(trimLeft(str));
}

var domainInvalidValidatorText = 'This field should be a URL in the format www.domain.com';
var domainValidator = /^((https?:\/\/)?([\-\w]+\.)+\w{2,3}([%\-\w]+(\.\w{2,})?)*)\/?$/i;
var broadKeyword = /^[ \u0080-\uFFFF \w \x27 \. \$ \+ \& \: \' \- \# \¹ \"]{1,1024}$/;
var exectKeyword = /^[[ \u0080-\uFFFF \w \x27 \. \$ \+ \& \: \' \- \# \¹ \"]{1,1024}]$/;
var phraseKeyword = /^"[ \u0080-\uFFFF \w \x27 \. \$ \+ \& \: \' \- \# \¹ \"]{1,1024}"$/;

function validateUrl(ev) {
    var url = domainValidator;

    if (document.getElementById('searchText').className != 'blackfont') {
        stopEvent(ev);
        return false;
    }
    
    var value = trimBoth(document.getElementById('searchText').value);

    if (!url.test(value) && !broadKeyword.test(value) && !exectKeyword.test(value) && !phraseKeyword.test(value)) {
    
        stopEvent(ev);

        Ext.Msg.alert('Error', 'The domain or keyword entered does not appear to be valid. Please check your submission and try entering it again (e.g. www.example.com).');
        return false;
    }
       
    return true;
}

var formSubmitted = false;
var isGuest = getCookie('Guest');

function submitForm(ev){   
    if (validateUrl(ev) === true)
    {
        if (!Ext.getCmp('googleCheckbox').checked &&
            !Ext.getCmp('yahooCheckbox').checked)
        {
            stopEvent(ev);
            Ext.Msg.alert('Error', 'No search engines were selected.');
            return false;
        }

        state.set('searchTextState', '');

        if (isRegister == "True") {
            if (checkRequestsLimitExceeded()) {
                stopEvent(ev);
                Ext.Msg.alert('Trial Research Report Limit Reached',
                    'During the ' + TrialPeriodDays + '-Day Trial period, you are able to run up to ' + TrialRequestCount + ' Research Reports<br>' +
                    'on competitors\' domains or keywords. <b>You have reached this limit already.</b><br>' +
                    '<br>' +
                    'You still have time to take advantage of the Monitoring feature where you may:' +
                    '<ul class="normal">' +
                    '<li>monitor up to ' + MaxMonitoredKeywords + ' keywords in up to ' + MaxMonitoredDomains + ' competitors\' domains, and</li>' +
                    '<li>set up email alerts to keep abreast of search engine position and ad changes.</li>' +
                    '</ul>' +
                    '<br>' +
                    'At any time, you may <a href="subscribe.aspx">subscribe</a> to the service to be able to run an unlimited number' +
                    'of Research Reports, and to continue monitoring your Keywords and Competitors. ' +
                    'SEO can be the most effective part of your marketing budget, so at $' + MonitoringSubscribePriceUsd + '/month,' +
                    'Keyword Competitor tool can more than pay for itself.');

                return false;
            }

            if (checkParallelRequestsLimitExceeded()) {
                stopEvent(ev);
                Ext.Msg.alert('Error', 'You have exceeded maximum(' + userLimits.MaxParallelRequests + ') number of concurrent requests.');
                return false;
            }
        } /*else {
            stopEvent(ev);
            RegisterWindowShow('research');
            return false;
        }*/

        if (!formSubmitted) {
            /*if (isRegister == "False")
            { 
                stopEvent(ev);    
                unregNotyPopup();      
            }*/

            
            if (isRegister == "False") {
                if ((typeof (pageTracker) != 'undefined') && (isGuest == null)) {
                    pageTracker._trackPageview('/users/gatrackGuestReports');
                }

                RegisterWindow.show();
                stopEvent(ev);
                return false;
            }

            if (!state.get('dontShowGeoWindow', false)) {
                GetLcationWindow.show();
                stopEvent(ev);
                return false;
            }
            
            formSubmitted = true;
            return true;
        }
        else
            return false;
    }
    else
        return false;
}

function unregNotyPopup()
{      
    var notifyForm = new Ext.form.FormPanel({      
        region: 'center',
        width: 250,
        border: false,
        monitorValid: true,
        monitorPoll: 150,
        margins: '3 0 3 3',
        cmargins: '3 3 3 3',
        bodyStyle: 'background: #EDD4C3; padding-top: 10px; padding-left: 5px;',
        defaultType: 'textfield',
        items: [{
            html: '<span style="font-size: 12px;">We can email you the report when it\'s done.</span>',
            name: 'label',
            xtype: 'label',
            width: 280
        },{
            name: 'email',
            allowBlank: false,
            vtype: 'email',
            hideLabel: true,
            style: 'margin-top: 5px;',
            width: 283
        }],
        buttons: [{
            text: 'OK',
            //formBind: true,
            handler: function() {
                if (!ValidateForm(notifyForm)) {
                    return;
                }
                var emailHidden = document.getElementById('unregUserEmail'); 
                emailHidden.value = notifyForm.getForm().findField('email').getValue();
                document.getElementById('form').submit();
            }
        },{
            text: 'No thank-you, I\'ll wait for it',
            minWidth: 187,
            handler: function() {
                document.getElementById('form').submit();
                mesNotify.hide();
            }
        }]
    });

    var mesNotify = new Ext.Window({
        title: 'No need to wait',
        closable: false,
        width: 320,
        height: 140,
        plain: true,
        layout: 'border',
        modal: true,
        resizable: false,
        items: [notifyForm]
    });

    mesNotify.show();
}

var emailValidator = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;

function checkEmail(fieldId) {
    var emailField = trimBoth(document.getElementById(fieldId).value);
    
    var sp = /\s/g;

    if (!emailValidator.test(emailField))
    {
         Ext.Msg.alert('Error', 'The address you entered, ' + emailField + ', does not appear to be a valid email address, please correct it so we can send the information to the right adress.');
        return false;
    }
    else
    {      
      if  (sp.test(emailField))
      {
            Ext.Msg.alert('Error', 'The address you entered, ' + emailField + ', does not appear to be a valid email address, please correct it so we can send the information to the right adress.');
            return false;
      }
      else
      {
            return true;        
      }
    }
}

function checkSite(fieldId) {
    var textField = document.getElementById(fieldId);

    if (!domainValidator.test(textField.value)) {
        Ext.Msg.alert('Error', 'The site you entered, does not appear to be a valid site name, please correct it.');
        return false;
    }
    else
        return true;
}

function checkForEmpty(fieldId, fieldName) {
    var textField = document.getElementById(fieldId);

    if (textField.value == '')
    {
        Ext.Msg.alert('Error', fieldName + ' field should not be empty.');
        return false;
    }
    else
        return true;
}

function signupSubmit(ev) {
    if (!checkForEmpty('master_pageContent_fname', 'First Name')) {
        stopEvent(ev);
        return false;
    }

    //else if (!checkForEmpty('master_pageContent_lname', 'Last Name'))
    //    stopEvent(ev);
    else if (!checkSite('master_pageContent_homesite')) {
        stopEvent(ev);
        return false;
    }
    else if (!checkEmail('master_pageContent_email')) {
        stopEvent(ev);
        return false;
    }
    //else if (!checkForEmpty('master_pageContent_password', 'Password'))
    //    stopEvent(ev);
    //else if (!checkForEmpty('master_pageContent_confirmPassword', 'Confirm Password'))
    //    stopEvent(ev);
    /*else if (document.getElementById('master_pageContent_password').value !==
             document.getElementById('master_pageContent_confirmPassword').value)
        {
            Ext.Msg.alert('Error', 'Password and Confirm Password do not mutch.');
            stopEvent(ev);
        }*/
    document.getElementById('master_pageContent_fname').value = trimBoth(document.getElementById('master_pageContent_fname').value);
    return true;
   //document.getElementById('master_pageContent_lname').value = trimBoth(document.getElementById('master_pageContent_lname').value);
}

function tellFriendSubmit(ev) {
    if (!checkEmail('master_pageContent_friendEmail'))
        stopEvent(ev);
    else if (!checkForEmpty('master_pageContent_userFirstName', 'First Name'))
        stopEvent(ev);
    else if (!checkForEmpty('master_pageContent_userLastName', 'Last Name'))
        stopEvent(ev);
    else if (!checkEmail('master_pageContent_yourEmail'))
        stopEvent(ev);
}

function signupSubmit2(ev) { 
       
    if (!checkForEmpty('master_fname', 'First Name'))
        stopEvent(ev);
    else if (!checkForEmpty('master_lname', 'Last Name'))
        stopEvent(ev);
    else if (!checkSite('master_homesite'))
        stopEvent(ev);
    else if (!checkEmail('master_email'))
        stopEvent(ev);
    else if (!checkForEmpty('master_password1', 'Password'))
        stopEvent(ev);
    else if (!checkForEmpty('master_confirmPassword', 'Confirm Password'))
        stopEvent(ev);
    else if (document.getElementById('master_password1').value !==
             document.getElementById('master_confirmPassword').value)
        {
            Ext.Msg.alert('Error', 'Password and Confirm Password do not mutch.');
            stopEvent(ev);
        }
    document.getElementById('master_fname').value = trimBoth(document.getElementById('master_fname').value);
    document.getElementById('master_lname').value = trimBoth(document.getElementById('master_lname').value);     
}

function showLoginPopup()
{   
    var loginPopup = document.getElementById('loginPopup');
    document.getElementById('loginPopupForm').reset();
    loginPopup.className = 'login-popup';
    document.getElementById('master_login').focus();
}

function closeLoginPopup()
{
    var loginPopup = document.getElementById('loginPopup');
    loginPopup.className = 'hidden';
}

function onLoginPopupSubmit(ev)
{
    if (document.getElementById('master_login').value == '' ||
        document.getElementById('master_password').value == '')
        stopEvent(ev);
    document.getElementById('master_login').value = trimBoth(document.getElementById('master_login').value);        
}

function onLoginPopupSubmit2(ev)
{
    if (document.getElementById('master_login2').value == '' ||
        document.getElementById('master_password2').value == '')
        stopEvent(ev);
    document.getElementById('master_login2').value = trimBoth(document.getElementById('master_login2').value);    
}


function showErrorMessage()
{
    if (document.getElementById('master_errorMessage') != null)
    {
        if (document.getElementById('master_errorMessage').value != '')
            Ext.Msg.alert('Error', document.getElementById('master_errorMessage').value);
    }
    else
        setTimeout(showErrorMessage, 100);        
}

function removeFavorite(id)
{
    var favoriteSites = document.getElementById('favoriteSites');
    
    if (favoriteSites != null)
    {
        for (var i = 0; i < favoriteSites.rows.length; i++)
        {
            if (favoriteSites.rows[i].id == ('fid-' + id))
            {
                favoriteSites.deleteRow(i);
                
                 var callback = {
                    success: function() {  },
                    failure: function() {  },
                    scope: this,
                    timeout : 10000
                };
                
                var params = 'fid=' + id;
                
                Ajax.request('POST', 'ajax.ashx', callback, params);
                break;
            }
        }
    }
}

function removeSaved(id)
{
    var favoriteSites = document.getElementById('savedSites');
    
    if (favoriteSites != null)
    {
        for (var i = 0; i < favoriteSites.rows.length; i++)
        {
            if (favoriteSites.rows[i].id == ('sid-' + id))
            {
                favoriteSites.deleteRow(i);
                
                 var callback = {
                    success: function() {  },
                    failure: function() {  },
                    scope: this,
                    timeout : 10000
                };
                
                var params = 'sid=' + id;
                
                Ajax.request('POST', 'ajax.ashx?', callback, params);
                break;
            }
        }
    }
}

var removeArray = new Array();
var removeIndex = 1;

function addToRemove(id)
{
    var chekboxRemove = document.getElementById('check-' + id);
    if (chekboxRemove.checked)
    {       
        removeArray[removeIndex] = id;
        removeIndex++;
    }
    else
    {        
        for (var i = 1; i <= removeArray.length; i++)
        {
            if (id == removeArray[i])
            {
                removeArray[i] = null;                
            }    
        }
    }
}

var removeArraySaved = new Array();
var removeIndexSaved = 1;

function addToRemoveSaved(id)
{
    var chekboxRemove = document.getElementById('check2-' + id);
    if (chekboxRemove.checked)
    {      
        removeArraySaved[removeIndexSaved] = id;
        removeIndexSaved++;
    }
    else
    {        
        for (var i = 1; i <= removeArraySaved.length; i++)
        {
            if (id == removeArraySaved[i])
            {
                removeArraySaved[i] = null;                
            }    
        }
    }
}

function deleteFavorits()
{
    var favoriteSites = document.getElementById('favoriteSites');
    
    if (favoriteSites != null)
    {
        for (var j = 1; j <= removeArray.length; j++)
        {
          if (removeArray[j] != null)
          {
            id = removeArray[j];
            for (var i = 0; i < favoriteSites.rows.length; i++)
            {
                if (favoriteSites.rows[i].id == ('fid-' + id))
                {                   
                    favoriteSites.deleteRow(i);
                    var callback = {
                        success: function() { },
                        failure: function() { },
                        scope: this,
                        timeout : 10000
                    };
                
                    var params = 'fid=' + id;
                
                    Ajax.request('POST', 'ajax.ashx', callback, params);
                    break;
                }
            }
          } 
       }
  }        
}

function deleteSaved()
{
    var favoriteSites = document.getElementById('savedSites');
    
    if (favoriteSites != null)
    {
        for (var j = 1; j <= removeArraySaved.length; j++)
        {
          if (removeArraySaved[j] != null)
          {
            id = removeArraySaved[j];
            for (var i = 0; i < favoriteSites.rows.length; i++)
            {
                if (favoriteSites.rows[i].id == ('sid-' + id))
                {
                    favoriteSites.deleteRow(i);
                
                    var callback = {
                        success: function() {  },
                        failure: function() {  },
                        scope: this,
                        timeout : 10000
                    };
                
                    var params = 'sid=' + id;
                
                    Ajax.request('POST', 'ajax.ashx', callback, params);
                    break;
                }
            }
          } 
       }
  }        
}

setTimeout(showErrorMessage, 100);