﻿var chooserRules = {
	'#Areas input': function(element) {
		element.onclick = function() {
			toggleCities(this);
		}
	},
	'#Groups input': function(element) {
		element.onclick = function() {
			toggleProfessions(this);
		}
	}
};
Behaviour.register(chooserRules);

var areasCount = 0;
var citiesCount = 0;
function toggleCities(area) {
	var on = area.checked;
	if (on && areasCount == 3) {
		alert('ניתן לבחור עד 3 אזורים');
		area.checked = false;
		return;
	}
	var citiesElement = $('CitiesArea' + area.value);
	if (on) {
		citiesElement.show(); 
		++areasCount;
	}
	else {
		citiesElement.hide();
		--areasCount;
	}
}

function toggleProfessions(group) {
	var on = group.checked;
	var groupProfessions = $$('.' + group.id);
	groupProfessions.each(function(p) { 
		if (on)
			$(p).show(); 
		else
			$(p).hide();
	});
}

var selectedAreas = [];
var selectedCities = [];
var selectedGroups = [];
var selectedProfessions = [];
function gatherData(form) {
	selectedCities = [];
	var cityContainers = $$('#Cities .SendDiv');
	cityContainers.each(function(cityContainer) {
	    if ($(cityContainer).visible()) {
			var cityElements = cityContainer.getElementsBySelector('.City input').findAll(function(city) {
				return city.checked;
			});
			if (cityElements.length == 0) {
				var areaId = parseInt(cityContainer.id.replace('CitiesArea', ''));
				selectedAreas.push(areaId);
			} else {
				cityElements.each(function(cityElement) {
					selectedCities.push(cityElement.value);
				});
			}
	    }
	});
	
	form['areas'].value = selectedAreas.join('|');
	form['cities'].value = selectedCities.join('|');
	
	selectedGroups = [];
	var form = $('SendResume');
	var professionContainers = $$('#Professions .SendDiv');
	professionContainers.each(function(professionContainer) {
		var groupId = parseInt(professionContainer.id.replace('ProfessionsGroup', ''));
		var professionElements = $(professionContainer).getElementsBySelector('.Profession input');
		var group = {
			id: groupId,
			professions: [],
			experienceOptionId: 0
		};
		professionElements.each(function(professionElement) {
			if (professionElement.checked)
				group.professions.push(professionElement.value);
		});
		if (group.professions.length > 0) {
			group.experienceOptionId = getRadioValue(form, 'Group' + group.id + 'ExperienceId');
			if (group.experienceOptionId == null)
				group.experienceOptionId = 0;
			selectedGroups.push(group);
		}
	});
	form['groups'].value = $A(selectedGroups).collect(function(group) {
		return group.id + ',' + group.experienceOptionId;
	}).join('|');
	
	selectedProfessions = $A(selectedGroups).pluck('professions').flatten();
	form['professions'].value = selectedProfessions.join('|');
}
function getRadioValue(form, name) {
	var radios = form[name];
	var radio = $A(radios).find(function(radio) {
		return radio.checked;
	});
	if (radio == null) return null;
	return radio.value;
}
var Validator = {
    'Email': /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,6}(\.[a-zA-Z]{2})?$/
};

function updateProfessionSelectBox(professionsElement, groupId) {
	professionsElement = $(professionsElement);
	new Ajax.Updater(professionsElement, siteRoot + '/Home/GetProfessionSelect.aspx', {
		method: 'get',
		parameters: 'groupId=' + groupId
	});
}

function showHelp() {
	window.open(siteRoot + '/Home/Help.aspx', 'help', 'width=300,height=440,left=100,top=100');
}

function showJobPreview(jobId) {
	window.open(siteRoot + '/Clients/Jobs/Preview.aspx?Id=' + jobId, 'preview', 'width=550,height=400,left=100,top=100');
}

function hashPassword(form) {
	form['password'].value = hex_sha256(form['otk'].value + hex_sha256($F('pwd')));
}

function sendTestMail(form, mailtype) {
	new Ajax.Request('SendTest' + mailtype + '.aspx', {
		method: 'post',
		parameters: Form.serialize(form),
		onSuccess: function(t) { alert(t.responseText); },
		onFailure: function(t) { alert(t.responseText); }
	});
}
function saveMessage(form) {
	$(form).request({
		method		: 'post',
		onSuccess	: function() {alert('השמירה בוצעה בהצלחה'); },
		onFailure	: function(t) {alert('השמירה נכשלה\r\n' + t.responseText); }
	});
}
function ismaxlength(obj)
{    
    var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length>mlength)
        obj.value=obj.value.substring(0,mlength)
}
function countChars(obj)
{
    if (1000 - obj.value.length < 0)
        $('charsLeft').innerHTML = 0;
    else
        $('charsLeft').innerHTML = 1000 - obj.value.length;
}
function cmtCountChars(obj, objId) {
    var limit = obj.getAttribute('maxlength') != undefined ? obj.getAttribute('maxlength') : 1000;
    
    if (limit - obj.value.length < 0)
        $(objId).innerHTML = 0;
    else
        $(objId).innerHTML = limit - obj.value.length;
}
function cutString(obj)
{
    obj.value = obj.value.substring(0,1000);
}
function cutString(str, length) {
    if (str.length > length)
        return str.substring(0, length) + ' ' + str.substring(length);
    return str;
}
function alertFailure()
{
    alert('הפעולה נכשלה, נסו שוב במועד מאוחר יותר');
}
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}
function validEmail(address) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(trim(address))}
function notNumeric(val) {
    return isNaN(val);
}
function clearForm(frmId) {
    var frm_elements = document.getElementById(frmId).elements;
    
    for (i = 0; i < frm_elements.length; i++) {
        field_type = frm_elements[i].type.toLowerCase();
        switch (field_type) {
            case "text":
            case "password":
            case "textarea":
            case "hidden":
                frm_elements[i].value = "";
                break;
            case "radio":
            case "checkbox":
                if (frm_elements[i].checked) {

                    frm_elements[i].checked = false;

                }
                break;
//            case "select-one":
//            case "select-multi":

//                frm_elements[i].selectedIndex = 0;
//                break;
            default:
                break;
        }
    }
}
function submitForm(frmId) {
    document.getElementById(frmId).submit();
}
function getToYearCombo(idPrefix) {
    var fromYear = $F(idPrefix + '_fromYear');
    $('fromYear').value = fromYear;
    $('idPrefix').value = idPrefix;

    $('frmCombo').request({
        onSuccess: function(t) {
            if (t.resposeText != '') {
                $(idPrefix + '_toYearWrap').update(t.responseText);
                if ($(idPrefix + '_chkToday').checked) {
                    $(idPrefix + '_toYear').selectedIndex = 0;
                    $(idPrefix + '_toYear').disabled = true;
                }
            }

        },
        onFailure: function(t) { alert('הפעולה נכשלה'); }
    });
    
//    new Ajax.Request(siteRoot + '/users/resumes/GetToYearCombo', {
//        method: 'post',
//        parameters: 'idPrefix=' + idPrefix + '&fromYear=' + fromYear,
//        onSuccess: function(transport) {
//            $('toYearWrap').update(transport.responseText);
//        }
//    });
}
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) {
    // the highlightStartTag and highlightEndTag parameters are optional
    if ((!highlightStartTag) || (!highlightEndTag)) {
        highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
        highlightEndTag = "</font>";
    }

    // find all occurences of the search term in the given text,
    // and add some "highlight" tags to them (we're not using a
    // regular expression search, because we want to filter out
    // matches that occur within HTML tags and script blocks, so
    // we have to do a little extra validation)
    var newText = "";
    var i = -1;
    var lcSearchTerm = searchTerm.toLowerCase();
    var lcBodyText = bodyText.toLowerCase();

    while (bodyText.length > 0) {
        i = lcBodyText.indexOf(lcSearchTerm, i + 1);
        if (i < 0) {
            newText += bodyText;
            bodyText = "";
        } else {
            // skip anything inside an HTML tag
            if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
                // skip anything inside a <script> block
                if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
                    newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
                    bodyText = bodyText.substr(i + searchTerm.length);
                    lcBodyText = bodyText.toLowerCase();
                    i = -1;
                }
            }
        }
    }

    return newText;
}
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag) {
    // if the treatAsPhrase parameter is true, then we should search for 
    // the entire phrase that was entered; otherwise, we will split the
    // search string so that each word is searched for and highlighted
    // individually
    if (treatAsPhrase) {
        searchArray = [searchText];
    } else {
        searchArray = searchText.split(" ");
    }

    if (!document.body || typeof (document.body.innerHTML) == "undefined") {
        if (warnOnFailure) {
            alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
        }
        return false;
    }

    var bodyText = document.body.innerHTML;
    for (var i = 0; i < searchArray.length; i++) {
        bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
    }

    document.body.innerHTML = bodyText;
    return true;
}
function highLightObject(htmlObjectId, term) {
    $(htmlObjectId).innerHTML = doHighlight($(htmlObjectId).innerHTML, term);
}
function isIE6() {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
        var ieversion = new Number(RegExp.$1);  // capture x.x portion and store as a number
        return (ieversion == 6);
    }
    return false;
}