﻿$jq.namespace('MatchCore.UI.ProfileEdit');

MatchCore.UI.ProfileEdit.Selection = function() {
    var _container;
    var _enableAny;
    var _anyElement;

    var unselect_checkbox = function() {
        var currentCheckbox = this;

        if (!currentCheckbox.checked)
            return;

        $jq(':checkbox, :radio', _container).each(function() {
            if ($jq(this).val() != "-1")
                this.checked = false;

        });
    };
    var select_all = function() {
        var currentCheckbox = this;

        if (!currentCheckbox.checked)
            return;

        $jq(':checkbox, :radio', _container).each(function() {
            if (!$jq(this).parent().hasClass('select_all'))
                this.checked = true;
        });
    };
    var select_none = function() {
        var currentCheckbox = this;

        if (!currentCheckbox.checked)
            return;

        $jq(':checkbox, :radio', _container).each(function() {
            if (!$jq(this).parent().hasClass('select_all'))
                this.checked = false;
        });

        currentCheckbox.checked = true;
    };
    var wireupControls = function() {

        $jq(':checkbox, :radio', _container).each(function() {
            var input = this;
            if ($jq(input).val() == "-1") {
                _anyElement = input;
                $jq(input).bind('click', unselect_checkbox);
            }
            else if ($jq(input).parent().hasClass('select_all')) {
                $jq(input).bind('click', select_all);
            }
            else if ($jq(input).parent().hasClass('select_none')) {
                $jq(input).bind('click', select_none);
            }
            else {
                $jq(input).bind('click', selection);
            }
        });
    };
    var selection = function() {
        var anySelected = false;
        if (_enableAny) {
            $jq(':checked', _container).each(function() {
                var input = this;
                if ($jq(input).val() != "-1") {
                    if ($jq(input).attr('checked'))
                        anySelected = true;
                }
            });
        }
        $jq('.select_all :checkbox, .select_all :radio', _container).attr('checked', false);
        if (!_enableAny) {
            $jq(_anyElement).attr('checked', false);
        }
        else {
            $jq(_anyElement).attr('checked', !anySelected);
        }
        $jq('.select_none :checkbox, .select_none :radio', _container).attr('checked', false);
    };
    var self = {
        init: function(opts) {
            if (opts != null && opts.container) {
                _container = opts.container;
                if (opts.meta.enableAny) {
                    _enableAny = true;
                }

                wireupControls();
            }
        }
    };
    return self;
};

MatchCore.UI.ProfileEdit.WordCount = function() {
    var _container;
    var _count = 0;
    var _maxinput = 0;
    
    var wireupControls = function() {
        $jq('textarea', _container).bind('keyup', function() {
            _count = _maxinput - $jq(this).val().length;
            
            if(_count >= 0)
                $jq('.counter', _container).text(_count);
            else {
                alert("Oops!  Please shorten your answer. Your answer can contain up to " +_maxinput+ " characters, including letters, numbers and underscores.  Watch the counter to tell how many characters you have remaining.");
                var text = $jq(this).val();
                text = text.substring(0, _maxinput);
                $jq(this).val(text);
                $jq('.counter', _container).text(0);
            }
        });
    };
    var self = {
        init: function(opts) {
            if (opts != null && opts.container) {
                _container = opts.container;
                _maxinput = opts.meta.maxcount;
                wireupControls();
                
                _count = _maxinput - ($jq('textarea', _container).val().length);
                $jq('.counter', _container).text(_count > 0 ? _count : 0);
            }
        }
    };
    return self;
};

MatchCore.UI.ProfileEdit.HtmlScrubber = function() {
    var _container;
    var _containerName;
    
    var wireupControls = function() {
        $jq('textarea', _container).bind('blur',function() {
            var form = this;
            var text = $jq(form).val();
            var regEx = new RegExp("<|%3C|>|%22|%3E|%2F|%3c|%3e|{|%2f/","g");
	        var m = regEx.exec(text);
    	    
            if (m) 
	        {
		        alert("\r\nPotentially dangerous characters were removed from the " + _containerName + "\r\n Characters like {<>\\} are not allowed\r\n");
	        } 
	        text = text.replace(regEx, "");
	        $jq(form).val(text);
        });
    };
    var self = {
        init: function(opts) {
            if (opts != null && opts.container) {
                _container = opts.container;
                _containerName = opts.meta.name;
                wireupControls();
            }
        }
    };
    return self;
};

MatchCore.UI.ProfileEdit.InnerContainer = function() {
    var _container;
    var _meta;
    var _values = [];
    
    var wireupControls = function() {
		if (_meta.form.toLowerCase() == "option") {
			$jq('.selection ' + _meta.form, _container).parents('SELECT').bind('change', function() {
				var selected = $jq('OPTION:selected', this).val();
				
				if(valueContains(selected)) {
					if(_meta.display == 'show') {
						display_container();
					}
					else {
						hide_container();
					}
				}
				else {
					if(_meta.display == 'show') {
						hide_container();
					}
					else {
						display_container();
					}
				}
			});			
		}
		
        $jq('.selection ' + _meta.form, _container).each(function() {
            var formvalue = $jq(this).val();
            
            if(valueContains(formvalue)) {
                if(_meta.display == 'show') {
					if (_meta.form.toLowerCase() != "option") {
						$jq(this).bind('click', display_container);
                    }
                    
                    if($jq(this).attr('selected') || $jq(this).attr('checked'))
                        display_container();
                }
                else {
					if (_meta.form.toLowerCase() != "option") {
						$jq(this).bind('click', hide_container);
                    }
                    
                    if($jq(this).attr('selected') || $jq(this).attr('checked'))
                        hide_container();
                }
            }
            else {
                if(_meta.display == 'show') {
					if (_meta.form.toLowerCase() != "option") {
						$jq(this).bind('click', hide_container);
                    }
                    
                    if($jq(this).attr('selected') || $jq(this).attr('checked'))
                        hide_container();
                }
                else {
					if (_meta.form.toLowerCase() != "option") {
						$jq(this).bind('click', display_container);
                    }
                    
                    if($jq(this).attr('selected') || $jq(this).attr('checked'))
                        display_container();
                }
            }
        });
    };
    var valueContains = function(opts) {
        for(var i = 0; i < _values.length; i++) {
            if(_values[i] === opts){
                return true;
            }
        }
        return false;
    };
    
    var display_container = function() {
        var visible = $jq('.innercontainer', _container).css('display') != 'none';
        if (!visible) {
            $jq('.innercontainer', _container).show();
        }
    };
    var hide_container = function() {
        var visible = $jq('.innercontainer', _container).css('display') != 'none';
        if (visible) {
            $jq('.innercontainer', _container).hide();
        }
    };
    var self = {
        init: function(opts) {
            if (opts != null && opts.container) {
                _container = opts.container;
                _meta = opts.meta
                _values = opts.meta.value;
                wireupControls();
            }
        }
    };
    return self;
};

MatchCore.UI.ProfileEdit.SeekLocation = function() {
	var _container;
	var _radiusPanel;
	var _regionPanel;
	
	var wireUpControls = function() {
		_radiusPanel = $jq('.geoRadiusPanel', _container).get(0);
		_regionPanel = $jq('.geoRegionPanel', _container).get(0);
		
		$jq('input:radio', _container).bind('click', function() {
			renderView();
		});
	};
	
	var renderView = function() {
		var rdoRadius = $jq('input:radio', _radiusPanel).get(0);
		var rdoRegion = $jq('input:radio', _regionPanel).get(0);
		
		if (rdoRadius.checked) {
			$jq('.geoPanelContent', _radiusPanel).show();
			$jq('.geoPanelContent', _regionPanel).hide();
		}
		else {
			$jq('.geoPanelContent', _radiusPanel).hide();
			$jq('.geoPanelContent', _regionPanel).show();
		}
	};
	
	var self = {
		init : function(opts) {
			if (opts != null) {
				if (opts.container != null)
					_container = opts.container;
				
				wireUpControls();
				renderView();
			}
		}
	};
	
	return self;
};

MatchCore.UI.ProfileEdit.Preference = function() {
    var _container;
    var _mustHave;
    var _firstSelection;

    var selection = function() {
        var currentCheckbox = this;

        if (!currentCheckbox.checked) {
            removeWeights();
            var visible = $jq('.importance', _container).css('display') != 'none';
            if (visible) {
                removeWeights();
                $jq('.importance', _container).hide();
            }
            return;
        }
        $jq(':checkbox', _container).each(function() {
            var noPreference = $jq(this).parent().hasClass('no_preference');
            if (!noPreference)
                this.checked = false;
        });
        var visible = $jq('.importance', _container).css('display') != 'none';
        if (visible) {
            removeWeights();
            $jq('.importance', _container).hide();
        }
    };
    var wireupControls = function() {
        var noPreferenceSelected = $jq('.no_preference :checkbox', _container).attr('checked');
        var anySelected = false;
        $jq(':checkbox', _container).each(function() {
            var input = this;
            if (!$jq(input).parent().hasClass('no_preference')) {
                $jq(input).bind('click', unselection);

                if ($jq(input).attr('checked'))
                    anySelected = true;
                if (noPreferenceSelected) {
                    $jq(input).attr('checked', false);
                }
            }
            else {
                $jq(input).bind('click', selection);
            }
        });

        if (noPreferenceSelected) {
            var visible = $jq('.importance', _container).css('display') != 'none';
            if (visible) {
                removeWeights();
                $jq('.importance', _container).hide();
            }
        }
        if (!noPreferenceSelected) {
            if (_mustHave && !$jq('.nice_to_have :radio', _container).attr('checked')) {
                $jq('.must_have :radio', _container).attr('checked', _mustHave);
            }
            else if (!_mustHave && !$jq('.must_have :radio', _container).attr('checked')) {
                $jq('.nice_to_have :radio', _container).attr('checked', !_mustHave);
            }
        }
        if (!noPreferenceSelected && !anySelected) {
            $jq('.no_preference :checkbox', _container).click();
        }
    };
    var unselection = function() {
        var anySelected = false;
        $jq(':checkbox', _container).each(function() {
            var input = this;
            if (!$jq(input).parent().hasClass('no_preference')) {
                if ($jq(input).attr('checked'))
                    anySelected = true;
            }
        });

        $jq('.no_preference :checkbox', _container).attr('checked', !anySelected);

        var visible = $jq('.importance', _container).css('display') != 'none';
        if (!visible && anySelected) {
            $jq('.must_have :radio', _container).attr('checked', _mustHave);
            $jq('.nice_to_have :radio', _container).attr('checked', !_mustHave);
            $jq('.importance', _container).show();
        }
        else if (visible && !anySelected) {
            removeWeights();
            $jq('.importance', _container).hide();
        }
    };
    var removeWeights = function() {
        $jq('.must_have :radio', _container).attr('checked', false);
        $jq('.nice_to_have :radio', _container).attr('checked', false);
    };
    var self = {
        init: function(opts) {
            if (opts != null && opts.container) {
                _container = opts.container;
                _mustHave = opts.meta.MustHave == 'true';
                wireupControls();
            }
        }
    };
    return self;
};

MatchCore.UI.ProfileEdit.HintText = function() {
	var _container = null;
	var _hintText = null;
	var _hasSelection = null;

    var wireupControls = function() {
        
        $jq(':radio, :checkbox', _container).each(function() {
            $jq(this).bind('click', _input_Click);
            $jq(this).bind('focus', _input_Click);
        });            
        
        $jq('select', _container).bind('change', _input_Click);
        
        $jq('textarea', _container).bind('click', _hideHint);
        $jq('textarea', _container).bind('blur', _showHint);
        $jq('textarea', _container).bind('focus',function() { 
            _hideHint(false);
        });
        
        $jq('.hint', _container).bind('click', function() {
            _hideHint(true)
        });
        $jq('.hint', _container).bind('focus', function() {
            _hideHint(true)      
        });
        $jq('.hint', _container).text(_hintText);
        
        if(_hasSelection) {
            if(_hasValidSelection()) {
                _activateTextArea();
                _showHint();
            }
            else {
                _deactivateTextArea();
                _showHint();
            }
        }
        else {
            _activateTextArea();
            _showHint();
        }
    };
    
    var _hasValidSelection = function () {
        var _returnValue = false;
        if(_hasSelection) {
            $jq(':radio, :checkbox', _container).each(function() {
	            if(this.checked && $jq(this).val() != '-1') {
	                _returnValue = true;
	            }
	        });
	        $jq('option:selected', _container).each(function() {
                if($jq(this).val() != '-1') {
                    _returnValue = true;
                }                
            });
        }
        else {
            _returnValue = true;
        }
        
        return _returnValue;
    };
    
    var _input_Click = function() {
        if(_hasSelection) {
            if(_hasValidSelection()) {
                _activateTextArea();  
            }         
            else {
                _deactivateTextArea();
            }   
        }
        else {
            _hideHint();
        }       
    };
    
    var _textarea_Click = function() {
        if(_hasSelection) {
            if(_hasValidSelection()) {
                _hideHint();
            }
            else {
                _showHint();
            }
        }
        else {
            _hideHint();
        }    
    };
    
    var _hint_Click = function() {
        if(_hasSelection) {
            if(_hasValidSelection()) {
                _hideHint();
                $jq('textarea', _container).focus();
            }
            else {
                _showHint();
            }
        }
        else {
            _hideHint();
        }
    };
    
    var _activateTextArea = function() {
        var textArea = $jq('textarea', _container);
        $jq(textArea).removeClass('textArea_hinted');
        $jq(textArea).addClass('textArea_active');
        $jq(textArea).removeAttr('disabled');
    };
    
    var _deactivateTextArea = function() {
        var textArea = $jq('textarea', _container);
        $jq(textArea).val('');
        textArea.trigger('keyup');
        $jq(textArea).removeClass('textArea_active');
        $jq(textArea).addClass('textArea_hinted');
        $jq(textArea).attr('disabled','disabled');
        _showHint();
    };
    
    var _showHint = function() {
        if($jq('textarea', _container).val() === '') {
            var hint = $jq('.hint', _container);
            $jq(hint).show();
        }
        else {
            _hideHint();
        }
    };
    
    var _hideHint = function(focusOnTextArea) {
        if(_hasValidSelection()) {
            var hint = $jq('.hint', _container);
            $jq(hint).hide();
            if(focusOnTextArea) {
                $jq('textarea', _container).focus();
            }
        }
    };

	var self = {
		init: function(opts) {
			if (opts != null && opts.container) {
				_container = opts.container;
				_hintText = opts.meta.hintText;
                _hasSelection = opts.meta.hasSelection;
				wireupControls();
			}
		}
	};
	return self;
};

MatchCore.UI.ProfileEdit.WeightedQuestion = function() {
    var _container;
    
    var wireupControls = function() {
        $jq(':radio, :checkbox', _container).each(function() {
            $jq(this).bind('click', removeWeightOption)
        });    
    };
    
    var hasValidOption = function() {
        var hasChecked = false;
        var returnValue = true;
        $jq(':checkbox', _container).each(function() {
            if(this.checked && $jq(this).parent().hasClass('unselect_all')) {
                hasChecked = true;
                returnValue = false;
            }
            if(this.checked) {
                hasChecked = true;
            }
        });
        if(!hasChecked) {
            $jq('.unselect_all :checkbox', _container).attr('checked', !hasChecked);
            returnValue = false;
        }
        return returnValue;        
    };
    
    var removeWeightOption = function() {
        if(!hasValidOption()) {
            $jq(':radio', _container).each(function() {
                if($jq(this).val() != 'ctl00') {
                    $jq(this).attr('checked', false);
                }
                else {
                    $jq(this).attr('checked', true);
                }
            });
            return;
        }   
    };

	var self = {
		init: function(opts) {
			if (opts != null && opts.container) {
				_container = opts.container;
				wireupControls();
			}
		}
	};
	
	return self;
}


MatchCore.UI.ProfileEdit.UserQuestion = function() {
    var _container = null;
    var _wasAnswered = false;
    var _answeredText = null;

    wireupControls = function() {
        $jq("#rdQuesYes", _container).click(function() {
            showPop();
        });
        $jq("#rdQuesNo", _container).click(function() {
            $jq("#unaskedQstBox", _container).hide();
        });
    };

    showRadios = function() {
        $jq('.unaskedQstOpt', _container).show();
    };

    showEdit = function() {
        $jq('.unaskedQstEdit', _container).show();
    };

    showPop = function() {
        $jq("#unaskedQstBox", _container).show();
    };

    render = function() {
        if (_wasAnswered) {
            showEdit();
            $jq('textarea', _container).attr('value', _answeredText);
        }
        else {
            showRadios();
        }
    };

    var self = {
        init: function(opts) {
            if (opts != null && opts.container) {
                _container = opts.container;
            }
            if (opts != null && opts.wasAnswered) {
                _wasAnswered = opts.wasAnswered;
            }

            if (opts != null && opts.answeredText) {
                _answeredText = opts.answeredText;
            }

            wireupControls();
            render();
        }
    };
    return self;
}

MatchCore.UI.ProfileEdit.OptInSpotLight = function() {
    var _service = new MatchCore.ServiceProxy(MatchCore.Application.resolveUrl('~/rest/MainService.ashx'));
    wireupControls = function() {
        $jq(':checkbox', _container).bind('click', submit);
    };
    var submit = function(e) {
        var isOptedIn = $jq(this).attr('checked');
		_service.invoke({
            verb: 'POST',
            method: 'OptInSpotlight',
            data: {
                'sid': MatchCore.Session.SID(),
                'theme': MatchCore.Session.ServerId(),
                'isOptedIn': isOptedIn
            }
        });
    };
    var self = {
        init: function(opts) {
            if (opts != null && opts.container) {
                _container = opts.container;
                wireupControls();
            }
        }
    };
    return self;
};

function ActivatePhotoUploadButton(obj)
{
    
    var divActiveButton = document.getElementById('UploadPhotoActive');
    var divStaticButton = document.getElementById('UploadPhotoStatic');
    var divActiveButton2 = document.getElementById('UploadPhotoActive2');
    var divStaticButton2 = document.getElementById('UploadPhotoStatic2');
    
    var divFileTypeError = document.getElementById('clientFileTypeError');
    var divFileSizeError = document.getElementById('clientFileSizeError');
    
    var allow = new Array('gif','png','jpg','bmp');
    var ext;
    var hasErrors = false;
    
    //hide the size error div onchange - client side
    divFileSizeError.style.display = "none";

    if ( obj != null && obj.value != null && obj.value != "")
    {
        // check file type -------------------------------------------------------------
        ext = obj.value.split('.').pop().toLowerCase();
        
        if($jq.inArray(ext, allow) == -1) //if file type not valid...
        {
            if (divFileTypeError != null)    //...show the file type error.
            {
                divFileTypeError.style.display = "inline";
            }
            
            hasErrors = true;
        }
        else    
            if (divFileTypeError != null) { divFileTypeError.style.display = "none"; } //otherwise, hide the error
        // end check file type ----------------------------------------------------------
        
        if (!hasErrors) //if there are no errors, show the active PHOTO UPLOAD button
        {
            divActiveButton.style.display = "inline"; //show active UPLOAD PHOTO button
            divActiveButton2.style.display = "inline"; //show active UPLOAD PHOTO button2
            divStaticButton.style.display = "none"; //hide just UPLOAD PHOTO image
            divStaticButton2.style.display = "none"; //hide just UPLOAD PHOTO image2
            $jq('#clientNoFileError').hide();
        }
    }
}
