﻿/// <reference path="ext-base.js" />
/// <reference path="ext-all.js" />

function hasKeywordMatchType() {

    var regExperssion = "(\"|\\u005B|\\u005D)";
    var re = new RegExp(regExperssion);
    var m = re.exec(Ext.getDom('searchText').value);
    
    if (m == null) {
        return false;
    }
    else {
        return true;
    }
}

function isReportByKeyword() {

    var re = new RegExp('^(([\\-\\w]+\\.)+\\w{2,3}([%\\-\\w]+(\\.\\w{2,})?)*)$', 'g');
    if (re.exec(Ext.getDom('searchText').value.replace('http://', '').replace('https://', '')) == null) {
        return true;
    }
    else {
        return false;
    }
}

function CreateMatchTypeArea() {

        return new Ext.form.FieldSet({
            title: 'Match Type',
            width: 335,
            height: 120,
            id: "matchTypeArea",
            items:
                    [
                        new Ext.form.Checkbox({
                            id: 'broadMatchTypeCheckbox',
                            checked: true,
                            labelSeparator: '',
                            hideLabel: true,
                            hidden: true,
                            boxLabel: 'Broad'
                        }),
                        
                       new Ext.form.Radio({
                           id: 'broadMatchTypeRadio',
                           checked: true,
                           labelSeparator: '',
                           hideLabel: true,
                           hidden: true,
                           boxLabel: 'Broad',
                           listeners: {
                               check: function(checkboxObject, checked) {
                                   if (checked == true) {
                                       Ext.getCmp('exactMatchTypeRadio').setValue(false);
                                       Ext.getCmp('phraseMatchTypeRadio').setValue(false);
                                   }
                               }
                           }
                       }),

                        new Ext.form.Checkbox({
                            id: 'exactMatchTypeCheckbox',
                            checked: false,
                            labelSeparator: '',
                            hideLabel: true,
                            hidden: true,
                            boxLabel: '[Exact]'
                        }),

                       new Ext.form.Radio({
                           id: 'exactMatchTypeRadio',
                           checked: false,
                           labelSeparator: '',
                           hideLabel: true,
                           hidden: true,
                           boxLabel: '[Exact]',
                           listeners: {
                               check: function(checkboxObject, checked) {
                                   if (checked == true) {
                                       Ext.getCmp('broadMatchTypeRadio').setValue(false);
                                       Ext.getCmp('phraseMatchTypeRadio').setValue(false);
                                   }
                               }
                           }
                       }),

                        new Ext.form.Checkbox({
                            id: 'phraseMatchTypeCheckbox',
                            checked: false,
                            labelSeparator: '',
                            hideLabel: true,
                            hidden: true,
                            boxLabel: '"Phrase"'
                        }),

                       new Ext.form.Radio({
                       id: 'phraseMatchTypeRadio',
                           checked: false,
                           labelSeparator: '',
                           hideLabel: true,
                           hidden: true,
                           boxLabel: '"Phrase"',
                           listeners: {
                               check: function(checkboxObject, checked) {
                                   if (checked == true) {
                                       Ext.getCmp('exactMatchTypeRadio').setValue(false);
                                       Ext.getCmp('broadMatchTypeRadio').setValue(false);
                                   }
                               }
                           }
                       })
                     ]
            })
}

var GetLcationWindow = new Ext.Window({
    title: 'Search The Web',
    width: 725, //385,
    height: 390, //305,
    autosize: true,
    plain: true,
    layout: 'table',
    layoutConfig: { columns: 2 },
    modal: true,
    resizable: false,
    closable: false,
    items: [new Ext.FormPanel({
        style: 'margin: 10px;',
        id: 'geoLocationPanel',
        bodyStyle: 'background-color: transparent;',
        border: false,
        items: [
            GeoLocationFieldset({
                title: 'Geo Location (limit search region)',
                window: 'geoWindow',
                height: 170
            })
        ,
        CreateMatchTypeArea()
        ]
    }),
    new Ext.FormPanel({
        style: 'margin: 10px;',
        id: 'customKeywordPanel',
        bodyStyle: 'background-color: transparent;',
        border: false,
        labelAlign: 'top',
        items: [
            new Ext.form.FieldSet({
                title: 'Use my specific keywords',
                width: 335,
                height: 299,
                items:
                [
                    new Ext.form.Checkbox({
                        id: 'useCustomKeywordsCheckbox',
                        checked: false,
                        //fieldLabel: '',
                        labelSeparator: '',
                        hideLabel: true,
                        boxLabel: 'Add these keywords to the search',
                        listeners: {
                            check: function(checkboxObject, checked) {
                                if (checked == true) {
                                    Ext.getCmp('keywordsTextArea').enable();
                                    var textValue = Ext.getCmp('keywordsTextArea').getValue();
                                    if (textValue.length > 0) {
                                        Ext.getCmp('searchOnlyCheckbox').enable();
                                    }
                                }
                                else {
                                    Ext.getCmp('keywordsTextArea').disable();
                                    Ext.getCmp('searchOnlyCheckbox').disable();
                                }
                            }
                        }
                    }),
                    {
                        xtype: 'textarea',
                        //labelWidth: 120,
                        fieldLabel: 'Enter one keyword or keyword phrase per line.<br>You can use "" or [] for match type', //or <a href="javascript:fpWindow.show();">import</a> from Excel.',
                        id: 'keywordsTextArea',
                        width: 310,
                        height: 145,
                        disabled: true,
                        //labelSeparator: '',
                        allowBlank: true,
                        enableKeyEvents: true,
                        listeners: {
                            keyup: function() {
                                var textValue = this.getValue();
                                if (textValue.length == 0) {
                                    Ext.getCmp('searchOnlyCheckbox').disable();
                                }
                                else {
                                    Ext.getCmp('searchOnlyCheckbox').enable();
                                }
                            }
                        }
                    },
                    {
                        html: '* Use CTRL+V to paste in keywords',
                        style: 'font-size: 10px;',
                        xtype: 'label'
                    },
                    new Ext.form.Checkbox({
                        id: 'searchOnlyCheckbox',
                        checked: false,
                        disabled: true,
                        //fieldLabel: '',
                        labelSeparator: '',
                        hideLabel: true,
                        boxLabel: 'Search only the keywords in the list above',
                        listeners: {
                            check: function(checkboxObject, checked) {
                                if (checked == true) {
                                    Ext.getCmp('broadMatchTypeCheckbox').disable();
                                    Ext.getCmp('exactMatchTypeCheckbox').disable();
                                    Ext.getCmp('phraseMatchTypeCheckbox').disable();
                                }
                                else {
                                    Ext.getCmp('broadMatchTypeCheckbox').enable();
                                    Ext.getCmp('exactMatchTypeCheckbox').enable();
                                    Ext.getCmp('phraseMatchTypeCheckbox').enable();
                                }
                            }
                        }
                    })
                ]
            })
        ]
    })

    ],

    buttonAlign: 'center',

    buttons: [
        {
            text: 'OK',
            handler: function() {

                //if (Ext.getCmp('geoWindowDontAsk').checked) {
                //    state.set('dontShowGeoWindow', true);
                //}

                if (!GetLcationWindow.monitoring) {
                    state.set('countryState', Ext.getCmp('geoWindowcountryCombo').value);
                    state.set('regionState', Ext.getCmp('geoWindowregionCombo').value);
                    state.set('cityState', Ext.getCmp('geoWindowcityCombo').value);

                    if (Ext.getCmp('useCustomKeywordsCheckbox').checked) {
                        var textValue = Ext.getCmp('keywordsTextArea').getValue();
                        if (textValue.length == 0) {
                            Ext.Msg.alert('Error', 'You did not enter any keywords. Either enter one or more keywords or deselect the checkbox.');
                            return;
                        }
                        Ext.getDom('customKeywords').value = escape(Ext.getCmp('keywordsTextArea').getValue());
                        if (Ext.getCmp('searchOnlyCheckbox').checked) {
                            Ext.getDom('searchOnlyTheKeywords').value = true;
                        }
                        else {
                            Ext.getDom('searchOnlyTheKeywords').value = false;
                        }
                    }

                    if (isReportByKeyword()) {
                        state.set('broadMatchType', Ext.getCmp('broadMatchTypeRadio').checked);
                        state.set('exactMatchType', Ext.getCmp('exactMatchTypeRadio').checked);
                        state.set('phraseMatchType', Ext.getCmp('phraseMatchTypeRadio').checked);
                    }
                    else {
                        state.set('broadMatchType', Ext.getCmp('broadMatchTypeCheckbox').checked);
                        state.set('exactMatchType', Ext.getCmp('exactMatchTypeCheckbox').checked);
                        state.set('phraseMatchType', Ext.getCmp('phraseMatchTypeCheckbox').checked);
                    }

                    Ext.getDom('changedCountry').value = Ext.getCmp('geoWindowcountryCombo').value;
                    if (Ext.getCmp('geoWindowregionCombo').disabled == false) {
                        Ext.getDom('changedRegion').value = Ext.getCmp('geoWindowregionCombo').value;
                    }
                    else {
                        Ext.getDom('changedRegion').value = '';
                    }

                    if (Ext.getCmp('geoWindowcityCombo').disabled == false) {
                        Ext.getDom('changedCity').value = Ext.getCmp('geoWindowcityCombo').value;
                    }
                    else {
                        Ext.getDom('changedCity').value = '';
                    }

                    document.getElementsByTagName('FORM')[0].submit();
                    GetLcationWindow.hide();
                    Ext.Msg.wait('Submitting a request...', 'Please wait...');
                } else {
                    GetLcationWindow.monitoringSettings.type = 'saveMonitoringInfo';
                    GetLcationWindow.monitoringSettings.gmtOffset = new Date().getGMTOffset(true);
                    GetLcationWindow.monitoringSettings.country = Ext.getCmp('geoWindowcountryCombo').value;
                    GetLcationWindow.monitoringSettings.region = Ext.getCmp('geoWindowregionCombo').value;
                    GetLcationWindow.monitoringSettings.city = Ext.getCmp('geoWindowcityCombo').value;

                    Ext.Ajax.request({
                        url: 'accountDataHandler.ashx',
                        params: GetLcationWindow.monitoringSettings,
                        success: function(result) {
                            if (Ext.decode(result.responseText).success) {
                                GetLcationWindow.hide();
                            } else {
                                Ext.Msg.alert('Error', 'Cannot save monitoring settings.');
                            }
                        },
                        failure: function() { Ext.Msg.alert('Error', 'Cannot save monitoring setttings.'); }
                    });
                }
            }
        }
    ],

    listeners: {
        show: function() {

            if (this.monitoring || isReportByKeyword()) {

                this.setWidth(375);

                if (this.monitoring || hasKeywordMatchType()) {

                    Ext.getCmp('broadMatchTypeCheckbox').show();
                    Ext.getCmp('exactMatchTypeCheckbox').show();
                    Ext.getCmp('phraseMatchTypeCheckbox').show();

                    Ext.getCmp('broadMatchTypeCheckbox').disable();
                    Ext.getCmp('exactMatchTypeCheckbox').disable();
                    Ext.getCmp('phraseMatchTypeCheckbox').disable();

                    Ext.getCmp('broadMatchTypeRadio').disable();
                    Ext.getCmp('exactMatchTypeRadio').disable();
                    Ext.getCmp('phraseMatchTypeRadio').disable();
                }
                else {
                    Ext.getCmp('broadMatchTypeRadio').show();
                    Ext.getCmp('exactMatchTypeRadio').show();
                    Ext.getCmp('phraseMatchTypeRadio').show();
                }
            }
            else {
                Ext.getCmp('broadMatchTypeCheckbox').show();
                Ext.getCmp('exactMatchTypeCheckbox').show();
                Ext.getCmp('phraseMatchTypeCheckbox').show();
            }

            var countryState = state.get('countryState', 'US');
            var regionState = state.get('regionState', '');
            var cityState = state.get('cityState', '');

            var updateGeoComntrols = function() {
                Ext.getCmp('geoWindowcountryCombo').setValue(countryState);
                var regionCombo = Ext.getCmp('geoWindowregionCombo');
                var cityCombo = Ext.getCmp('geoWindowcityCombo');

                if (countryState == '') {
                    settingsPanel.updateState = true;
                    settingsPanel.updateTitle();
                }
                else {
                    regionCombo.emptyText = 'Loading...';
                    regionCombo.reset();

                    //regionCombo.getEl().up('.x-form-item').down('label').dom.innerHTML = record.data.region + ':';
                    regionCombo.store.on('load', function() {

                        regionCombo.emptyText = 'All regions within this country';
                        if (regionCombo.store.getCount() == 0)
                            regionCombo.setDisabled(true);
                        if (regionState == '') {
                            //regionCombo.setDisabled(true);
                            regionCombo.reset();
                        }
                        else
                            regionCombo.setValue(regionState);

                    }, regionCombo, { single: true });

                    regionCombo.store.load({ params: { country: countryState} });
                }

                if (regionState != '') {
                    cityCombo.emptyText = 'Loading...';
                    cityCombo.reset();

                    //regionCombo.getEl().up('.x-form-item').down('label').dom.innerHTML = record.data.region + ':';
                    cityCombo.store.on('load', function() {
                        cityCombo.emptyText = 'All cities within this region';

                        if (cityCombo.store.getCount() == 0)
                            cityCombo.setDisabled(true);

                        if (cityCombo == '') {
                            cityCombo.reset();
                        }
                        else
                            cityCombo.setValue(cityState);

                    }, cityCombo, { single: true });

                    cityCombo.store.load({ params: { region: regionState} });
                }
            };

            if (this.monitoring) {
                Ext.Ajax.request({
                    url: 'accountDataHandler.ashx',
                    params: { type: 'monitoringSettings', gmtOffset: new Date().getGMTOffset(true) },
                    failure: function() {
                        Ext.Msg.alert('Error', 'Cannot load the settings.');
                    },
                    success: function(result) {
                        result = Ext.decode(result.responseText);

                        Ext.Msg.hide();

                        if (result.success) {
                            var monitoringSettings = result.extraData;
                            countryState = monitoringSettings.country;
                            regionState = monitoringSettings.region;
                            cityState = monitoringSettings.city;

                            GetLcationWindow.monitoringSettings = monitoringSettings;
                            updateGeoComntrols();
                        }
                    }
                });
            } else {
                updateGeoComntrols();
            }
        }
    }
});

var showFunction = GetLcationWindow.show;

GetLcationWindow.show = function(type) {
    if (type == 'monitoring') {
        GetLcationWindow.monitoring = true;
    }
    showFunction.createDelegate(GetLcationWindow)();
}
