/// <reference path="Globals.js">
/// <reference path="validationFunctions.js">
/// <reference path="GlobalsTop.js">

/******************
Registration Form
*******************/

Event.observe(window, "load", function()
    {
        var hoursOfOp = $('hoursOfOp');
        if(hoursOfOp != null)
        {
            var val = hoursOfOp.value;
            //alert('hoursOfOp = ' + val);
            if(val != null && val != "")
            {
                var selects = $$('#OpenHours select');
                var hoursArr = val.split(",");
                for(var i = 0; i < hoursArr.length; i++)
                {
                        if(hoursArr[i] != "Closed" && hoursArr[i] != "Open24hrs")
                        {
                            var dayHoursArr = hoursArr[i].split(" - ");
                            setSelectIndex(selects[i*2], dayHoursArr[0]);
                            setSelectIndex(selects[(i*2)+1], dayHoursArr[1]);
                        }
                        else
                        {
                            if(hoursArr[i] == "Closed")
                            {
                                selects[i*2].selectedIndex = 49;
                            }
                            else
                            {
                                selects[i*2].selectedIndex = 50;
                            }
                            selects[(i*2)+1].disabled = true;
                        }
                }
                var list = $('DisplayHoursContainer');
                if(list)
                {
                    var j = 0;
                    while(list.hasChildNodes()) list.removeChild(list.firstChild);
                    for(i = 0; i < selects.length; i += 2)
                    {
                        var valToInsert = "";
                        if(selects[i].options[selects[i].selectedIndex].value == "Open24hrs" || selects[i+1].options[selects[i+1].selectedIndex].value == "Open24hrs")
                        {
                            valToInsert = "Open24hrs";
                        }
                        else if(selects[i].options[selects[i].selectedIndex].value == "Closed" || 
                                selects[i+1].options[selects[i+1].selectedIndex].value == "Closed" ||
                                selects[i].options[selects[i].selectedIndex].value == 0 || 
                                selects[i+1].options[selects[i+1].selectedIndex].value == 0)
                        {
                            valToInsert = "Closed";
                        }
                        else
                        {
                            valToInsert = selects[i].options[selects[i].selectedIndex].text + " - " + selects[i+1].options[selects[i+1].selectedIndex].text;
                        }
                        new Insertion.Bottom(list, "<li><div class='first Left'>" + days[j++] + "</div><div class='Left'>" + valToInsert + "</div><div class='Break'></div></li>");
                    }
                }
            }
        }
    });
    
function setSelectIndex(select, val)
{
    for(var i = 0; i < select.options.length; i++)
    {
       if(select.options[i].value == val)
       {
            select.selectedIndex = i;
            return;
       }
    }
}

function submitEditForumForm(form)
{
    var form = $(form);
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false; 
    
    validateNotEmpty2({elem: $('forumManagerName'), Error: Error, fieldName: "the name of the forum"});	
    validateNotEmpty2({elem: $('forumManagerWebsite'), Error: Error, fieldName: "the url of the forum"});
    validateNotEmpty2({elem: $('forumDescription'), Error: Error, fieldName: "the forum description"});
    gatherConditionsData(Error, 'ForumConditionsContainer', 'forum');
    
    var pics = $$('.AddPicture');
	for(var i = 0; i < pics.length; i++)
	{
	    if(pics[i] && pics[i].value.length > 0)	
        {    
            validateRegEx2({elem: pics[i],  Error: Error, pattern: /^(.+\.(jpg|gif|jpeg|png))?$/i  });
	    }
	}
	
	if(!Error.found)
	{
	    var btSave = $('btSave');
        btSave.onclick = function (){return false;};
        
        showProgressBarDialog();         
        form.submit();
	}
	else
	{
	    if(Error.elementToFocus != null)
	        Error.elementToFocus.focus();
    }
}

function submitForumRegistrationForm(form, toCreateAnotherForumPage, type)
{
    var form = $(form);
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false; 
    
    if(type == 'forumManager')
	{
	    validateNotEmpty2({elem: $('forumManagerName'), Error: Error, fieldName: "the name of the forum"});	
        validateNotEmpty2({elem: $('forumManagerWebsite'), Error: Error, fieldName: "the url of the forum"});
        validateNotEmpty2({elem: $('forumDescription'), Error: Error, fieldName: "the forum description"});
        gatherConditionsData(Error, 'ForumConditionsContainer', 'forum');
	}
	var pics = $$('.AddPicture');
	for(var i = 0; i < pics.length; i++)
	{
	    if(pics[i] && pics[i].value.length > 0)	
        {    
            validateRegEx2({elem: pics[i],  Error: Error, pattern: /^(.+\.(jpg|gif|jpeg|png))?$/i  });
	    }
	}
	
	if(!Error.found)
	{
	    var createAnotherForum = $('createAnotherForum');
	    if(toCreateAnotherForumPage)
	    {
	        createAnotherForum.value = "true";
        }
        else
        {
            createAnotherForum.value = "false";
        }    
	
	    var btSubmitRegistration = $('btSubmitRegistration');
        btSubmitRegistration.onclick = function (){return false;};    
	        
        var btSubmitAndNewRegistration = $('btSubmitAndNewRegistration');
        btSubmitAndNewRegistration.onclick = function (){return false;};
        
        showProgressBarDialog();         
        form.submit();
	}
	else
	{
	    if(Error.elementToFocus != null)
	        Error.elementToFocus.focus();
    }
}

    
var ingredientIdsHash = new Hash();
function submitRegistrationForm(form, toCreatePersonalPage, type)
{    
    var form = $(form);
    var Error = {};
    Error.elementToFocus = null;
    Error.found = false; 
    
    // check for valid email
	var email = $('Email');
    var validEmail = validateEmail(email, 'EmailErrorContainer', "Incorrect or incomplete email address", Error);
    validateStringsMatch(email, $('RetypedEmail'), 
		'RetypeEmailErrorContainer', "Original and re-typed email do not match", Error);
    
	//var name = form.getElementsBySelector('input[id=Name]')[0];	
	//validateNotEmpty2({elem: name, Error: Error, fieldName: "a screen name"});
	var name = $('Name');
	var pattern = /^[a-zA-Z0-9\s\._-]{2,13}$/;	    
	validateRegEx(name, 'UsernameErrorContainer', "Can contain only letters, digits, space, '_', '.' and '-' and between 2 to 13 characters", pattern, Error);
	
	var password = $('Password');
	// check for valid password and matching password and retyped password
	validatePassword(password, 'PasswordErrorContainer', Error );	
	
	// check for valid password and matching password and retyped password
    validateStringsMatch(password, $('RetypedPassword'), 
		'RetypePasswordErrorContainer', "Original and re-typed password do not match", Error);
		
	if(type == 'supplier')
	{	
        validateNotEmpty2({elem: $('supplierName'), Error: Error, fieldName: "the name of your store"});	
        validateNotEmpty2({elem: $('supplierStreet'), Error: Error, fieldName: "the street of your store"});
        validateNotEmpty2({elem: $('supplierStreetNumber'), Error: Error, fieldName: "the street number"});
        validateNotEmpty2({elem: $('supplierCity'), Error: Error, fieldName: "the city of your store"});
        validateNotEmpty2({elem: $('supplierZip'), Error: Error, fieldName: "the zip/postal code"});
        validateNotEmpty2({elem: $('supplierPhoneArea'), Error: Error, fieldName: "a phone area", valToExclude: 'Area'});
	    validateNotEmpty2({elem: $('supplierPhoneNumber'), Error: Error, fieldName: "a phone number", valToExclude: 'Number'});
        validateEmail2({elem: $('supplierEmail'), errorMsg: "Incorrect or incomplete email address", Error: Error  } );
	}	
	else if(type == 'forumManager')
	{
	    validateNotEmpty2({elem: $('forumManagerName'), Error: Error, fieldName: "the name of the forum"});	
        validateNotEmpty2({elem: $('forumManagerWebsite'), Error: Error, fieldName: "the url of the forum"});
        validateNotEmpty2({elem: $('forumDescription'), Error: Error, fieldName: "the forum description"});
        gatherConditionsData(Error, 'ForumConditionsContainer', 'forum');
	}
	else if(type == 'healthExpert')
	{
	    validateNotEmpty2({elem: $('userFirstName'), Error: Error, fieldName: "your first name"});	
        validateNotEmpty2({elem: $('userLastName'), Error: Error, fieldName: "your last name"});
	    
	    //validateNotEmpty2({elem: $('expertTitle'), Error: Error, fieldName: "your title"});	
        validateNotEmpty2({elem: $('expertName'), Error: Error, fieldName: "the name of your clinic"});	
        //validateNotEmpty2({elem: $('expertStreet'), Error: Error, fieldName: "the street of your clinic"});
        //validateNotEmpty2({elem: $('expertStreetNumber'), Error: Error, fieldName: "the street number"});
        //validateNotEmpty2({elem: $('expertCity'), Error: Error, fieldName: "the city of your clinic"});
        //validateNotEmpty2({elem: $('expertZip'), Error: Error, fieldName: "the zip/postal code"});
        validateNotEmpty2({elem: $('expertPhoneArea'), Error: Error, fieldName: "a phone area", valToExclude: 'Area'});
	    validateNotEmpty2({elem: $('expertPhoneNumber'), Error: Error, fieldName: "a phone number", valToExclude: 'Number'});
        validateEmail2({elem: $('expertEmail'), errorMsg: "Incorrect or incomplete email address", Error: Error  } );
	    gatherConditionsData(Error, 'ExpertConditionsContainer', 'expert');
	}
	
	var pics = $$('.AddPicture');
	for(var i = 0; i < pics.length; i++)
	{
	    if(pics[i] && pics[i].value.length > 0)	
        {    
            validateRegEx2({elem: pics[i],  Error: Error, pattern: /^(.+\.(jpg|gif|jpeg|png))?$/i  });
	    }
	}
	
	if(type == 'supplier')
	{
	    var country = form.getElementsBySelector('select[id=supplierCountry]')[0];
	    if(country)
	    {
	        validateSelect({elem: country, fieldName: "Country", Error: Error, valToValidate: "0"});
	        if(country.options[country.selectedIndex].value == "1")
	        {
                validateSelect({elem: form.getElementsBySelector('select[id=supplierState]')[0], fieldName: "State", Error: Error});
	        }
	    }
	    validateSelect({elem: $('supplierShipping'), fieldName: "Shipping option", Error: Error});
	}
	if(type == "healthExpert")
	{
	    var country = form.getElementsBySelector('select[id=expertCountry]')[0];
	    if(country)
	    {
	        validateSelect({elem: country, fieldName: "Country", Error: Error, valToValidate: "0"});
	        if(country.options[country.selectedIndex].value == "1")
	        {
                validateSelect({elem: form.getElementsBySelector('select[id=expertState]')[0], fieldName: "State", Error: Error});
	        }
	    }
	}
	
	// check for not empty Captcha
    validateLength($('Captcha'), 'CaptchaErrorContainer', 4, 4, "Please enter the code shown in the image below", Error);  
    //validateLength($('Captcha'), 'CaptchaErrorContainer', 4, 4, "Please enter the code shown in the image below", Error, "Please enter the code shown in the image");    
	  
	
	// check for UserAgreed checked
	validateUserAgreement($('UserAgreed'), 'UserAgreedErrorContainer',
		"You must review and accept the terms of service and privacy policy", Error );	 
	
	if(type == 'supplier')
	{
	    var ingredientIds = $('ingredientIds');	
	    validateIngredientIdsHash({elem: ingredientIds, hash: ingredientIdsHash, Error: Error});
	    validateCheckboxsChecked({elem: $('supplierProducts'), Error: Error});
	    //validateHours(Error, "store");	
	}
	else if(type == "healthExpert")
	{
//	    validateCheckboxsChecked({elem: $('expertAppointments'), Error: Error});
//	    gatherServicesData(Error, 'ServicesContainer', 'expert');
//	    validateHours(Error, "clinic");	
	}
	
	if(!Error.found)
	{
	    var createPersonalPage = $('createPersonalPage');
	    if(toCreatePersonalPage)
	    {
	        createPersonalPage.value = "true";
        }
        else
        {
            createPersonalPage.value = "false";
        }    
        var btSubmitRegistration = $('btSubmitRegistration');
        btSubmitRegistration.onclick = function (){return false;};
        var btSubmitAndNewRegistration = $('btSubmitAndNewRegistration');
        btSubmitAndNewRegistration.onclick = function (){return false;}; 
        
        showProgressBarDialog();         
        
        if(type == 'supplier')
	    {
            if(ingredientIds)
            {
                ingredientIds.value = ingredientIdsHash.values().join(':');
            }
        }
        if(type == 'supplier' || type == 'healthExpert')
	    {
            setHours();
            var hours = $('hoursOfOp');
            if(hours)
            {
                hours.value = hoursArr.join(',');
            }
        }
        form.submit();
	}
	else
	{
	    if(Error.elementToFocus != null)
	        Error.elementToFocus.focus();
        
    }
}

function gatherServicesData(Error, containerId, prefix)
{
    var newServices = $$('#' + containerId + ' select');
	i = 0;
	newServices.each(function (newService) {
    	    newService.name = prefix + 'NewServicesIds['+ i +']';
		    ++i;
	});
	var existingServices = $$('#' + containerId + ' .ExistingService input[type=hidden]');
	
	if(existingServices.length > 0)
	{
	    i = 0;
        existingServices.each(function (existingService) {
		    existingService.name = prefix + 'ExistingServicesIds['+ i +']';
		    ++i;
	    });
	}
	else
	{
	    validateItemSelected(Error, i, newServices, 'ServicesErrorContainer');
	}
}

function gatherConditionsData(Error, containerId, prefix)
{
    var newConditions = $$('#' + containerId + ' select');
	i = 0;
    newConditions.each(function (newCondition) {
		newCondition.name = prefix + 'ConditionIds['+ i +']';
		++i;
	});
	
	var existingConditions = $$('#' + containerId + ' .ExistingConditionContainer input[type=hidden]');
	if(existingConditions.length > 0)
	{
	    i = 0;
        existingConditions.each(function (existingCondition) {
		    existingCondition.name = prefix + 'ExistingConditionIds['+ i +']';
		    ++i;
	    });
	}
	else
	{
	    validateItemSelected(Error, i, newConditions, 'ConditionErrorContainer');
	}
	
	var existingSpecificConditions = $$('#' + containerId + ' .ExistingSpecificConditionContainer input[type=hidden]');
	if(existingSpecificConditions.length > 0)
	{
	    i = 0;
        existingSpecificConditions.each(function (existingSpecificCondition) {
		    existingSpecificCondition.name = prefix + 'ExistingSpecificConditionIds['+ i +']';
		    ++i;
	    });
	}
	
	
	var newSpecificConditions = $$('#' + containerId + ' .SpecificConditionsSelect');
    i = 0;
	newSpecificConditions.each(function (newSpecificCondition) {
		//if(parseInt(newSpecificConditions.value) > 0)
			newSpecificCondition.name = prefix + 'SpecificConditionIds['+ i +']';
		++i;
	});
}

Event.observe(window, "load", setIngredientIdsHash);
function setIngredientIdsHash()
{
    var ingredientIds = $('ingredientIds');	
    if(ingredientIds)
    {
        var ingredientIdsArr = ingredientIds.value.split(':');
        for(var i = 0; i < ingredientIdsArr.length; i++)
        {
            if(ingredientIdsArr[0].length > 0)
            {
                ingredientIdsHash.set(ingredientIdsArr[i], ingredientIdsArr[i]);
            }
        }
        selectCheckboxes();
        
    }
}

function selectCheckboxes()
{
    var checkboxes = $$('#HerbChooserOuter input[type=checkbox]');
    for(var i = 0; i < checkboxes.length; i++)
    {
        if(typeof ingredientIdsHash.get(checkboxes[i].value) != 'undefined')
        {
            checkboxes[i].checked = true;
            $(checkboxes[i]).up().getElementsBySelector("a")[0].addClassName("selected");
        }
    }
}

function changeIngredientsList(checkbox)
{
    if(checkbox.checked)
    {
        ingredientIdsHash.set(checkbox.value, checkbox.value);
        $(checkbox).up().getElementsBySelector("a")[0].addClassName("selected");
        
    }
    else
    {
        ingredientIdsHash.unset(checkbox.value);
        var checkboxes = $$('#HerbChooserOuter input[type=checkbox]');
        for(var i = 0; i < checkboxes.length; i++)
        {
            if(checkboxes[i].value == checkbox.value)
            {
                checkboxes[i].up().getElementsBySelector("a")[0].removeClassName("selected");
                checkboxes[i].checked = false;
            }
        }
    }
}

/******************
Edit user form
*******************/
function submitEditUserForm(type)
{
   	var form = $('EditUserForm');
   	var Error = {};
    Error.elementToFocus = null;
    Error.found = false;      
   
	if(type == 'regular')
	{
	     //AboutMyself
        var aboutMyself = form.getElementsBySelector('textarea[id=AboutMyself]')[0];
 	    validateLength(aboutMyself, 'EditUserAboutMyselfErrorContainer', 0, 200, 
		    "A few words about yourself cannot exceeds 200 characters", Error); 
    	
	    gatherUserData(form);
    	
	    var fileExtensionPattern = /^(.+\.(jpg|gif|jpeg|png))?$/i;	
        var newImages = $$('#AddPicturesContainer input[type=file]');
	    for(var i = 0; i < newImages.length; i++)
	    {
		    if(newImages[i].value.length > 0)
		    {    
		        if(!validateRegEx(newImages[i], 'ImageErrorContainer', "Please provide a valid image extension (jpeg, jpg, gif, png)", fileExtensionPattern, Error))
		            break;
	        }
	    }
	}
	
	if(type == 'supplier')
	{
	    validateNotEmpty2({elem: $('supplierName'), Error: Error, fieldName: "the name of your store"});	
        validateNotEmpty2({elem: $('supplierStreet'), Error: Error, fieldName: "the street of your store"});
        validateNotEmpty2({elem: $('supplierStreetNumber'), Error: Error, fieldName: "the street number"});
        validateNotEmpty2({elem: $('supplierCity'), Error: Error, fieldName: "the city of your store"});
        validateNotEmpty2({elem: $('supplierZip'), Error: Error, fieldName: "the zip/postal code"});
        validateNotEmpty2({elem: $('supplierPhoneArea'), Error: Error, fieldName: "a phone area", valToExclude: 'Area'});
	    validateNotEmpty2({elem: $('supplierPhoneNumber'), Error: Error, fieldName: "a phone number", valToExclude: 'Number'});
        validateEmail2({elem: $('supplierEmail'), errorMsg: "Incorrect or incomplete email address", Error: Error  } );
	}
	else if(type == 'healthExpert')
	{
	    validateNotEmpty2({elem: $('userFirstName'), Error: Error, fieldName: "your first name"});	
        validateNotEmpty2({elem: $('userLastName'), Error: Error, fieldName: "your last name"});
        
	    //validateNotEmpty2({elem: $('expertTitle'), Error: Error, fieldName: "your title"});	
        validateNotEmpty2({elem: $('expertName'), Error: Error, fieldName: "the name of your clinic"});	
        //validateNotEmpty2({elem: $('expertStreet'), Error: Error, fieldName: "the street of your clinic"});
        //validateNotEmpty2({elem: $('expertStreetNumber'), Error: Error, fieldName: "the street number"});
        //validateNotEmpty2({elem: $('expertCity'), Error: Error, fieldName: "the city of your clinic"});
        //validateNotEmpty2({elem: $('expertZip'), Error: Error, fieldName: "the zip/postal code"});
        validateNotEmpty2({elem: $('expertPhoneArea'), Error: Error, fieldName: "a phone area", valToExclude: 'Area'});
	    validateNotEmpty2({elem: $('expertPhoneNumber'), Error: Error, fieldName: "a phone number", valToExclude: 'Number'});
        validateEmail2({elem: $('expertEmail'), errorMsg: "Incorrect or incomplete email address", Error: Error  } );
        //gatherServicesData(Error, 'ServicesContainer', 'expert');
        gatherConditionsData(Error, 'ExpertConditionsContainer', 'expert');
        //validateCheckboxsChecked({elem: $('expertAppointments'), Error: Error});
	    //validateHours(Error, "clinic");	
	    
	    var country = form.getElementsBySelector('select[id=expertCountry]')[0];
	    if(country)
	    {
	        validateSelect({elem: country, fieldName: "Country", Error: Error, valToValidate: "0"});
	        if(country.options[country.selectedIndex].value == "1")
	        {
                validateSelect({elem: form.getElementsBySelector('select[id=expertState]')[0], fieldName: "State", Error: Error});
	        }
	    }
	}
	
	if(type == 'regular')
	{
	    var userPic = $('userPic');
	    if(userPic && userPic.value.length > 0)	
        {    
            validateRegEx2({elem: userPic,  Error: Error, pattern: /^(.+\.(jpg|gif|jpeg|png))?$/i  });
	    }
	}
	
	if(type == 'supplier')
	{
	    var country = form.getElementsBySelector('select[id=supplierCountry]')[0];
	    if(country)
	    {
	        validateSelect({elem: country, fieldName: "Country", Error: Error, valToValidate: "0"});
	        if(country.options[country.selectedIndex].value == "1")
	        {
                validateSelect({elem: form.getElementsBySelector('select[id=supplierState]')[0], fieldName: "State", Error: Error});
	        }
	    }
	    validateSelect({elem: $('supplierShipping'), fieldName: "Shipping option", Error: Error});
	    //validateHours(Error, "store");
	
	    var ingredientIds = $('ingredientIds');	
	    validateIngredientIdsHash({elem: ingredientIds, hash: ingredientIdsHash, Error: Error});
	    validateCheckboxsChecked({elem: $('supplierProducts'), Error: Error});	
	}
	else if(type == 'forumManager')
	{
	    validateNotEmpty2({elem: $('forumManagerName'), Error: Error, fieldName: "the name of the forum"});	
        validateNotEmpty2({elem: $('forumManagerWebsite'), Error: Error, fieldName: "the url of the forum"});
        validateNotEmpty2({elem: $('forumDescription'), Error: Error, fieldName: "the forum description"});
        gatherConditionsData(Error, 'ForumConditionsContainer', 'forum');
	}
	
	if(Error.found == false)
	{
        if(type == 'supplier' || type == 'healthExpert')
	    {
            setHours();
            var hours = $('hoursOfOp');
            if(hours)
            {
                hours.value = hoursArr.join(',');
            }
        }
        
        
        
        //alert(hoursArr.length);
        if(ingredientIds)
        {
            ingredientIds.value = ingredientIdsHash.values().join(':');
        }
        
        var btSubmitEditUser = $('btSubmitEditUser');
        btSubmitEditUser.onclick = function (){return false;};
        showProgressBarDialog();
        
	    form.submit();
	    return true;
	}
	else
	{    
	    if(Error.elementToFocus != null)
	        Error.elementToFocus.focus();
	    return false;
    }
}


function gatherUserData(form) {
	var i = 0;

	var existingImageIds = $$('#AddPicturesContainer input[type=hidden]');
	i = 0;
	existingImageIds.each(function (existingImageId) {
		existingImageId.name = 'existingImageIds['+ i +']';
		++i;
	});
	
	var existingConditionIds = $$('#ConditionsContainer input[type=hidden]');
	i = 0;
	existingConditionIds.each(function (existingConditionId) {
		existingConditionId.name = 'existingConditionIds['+ i +']';
		++i;
	});

	var newImages = $$('#AddPicturesContainer input[type=file]');
	i = 0;
	newImages.each(function (newImage) {
		newImage.name = 'images['+ i +']';
		++i;
	});
	
	var newConditions = $$('#ConditionsContainer select');
    i = 0;
    newConditions.each(function (newCondition) {
        if(newCondition.selectedIndex != 0)
		{
		    newCondition.name = 'conditionIds['+ i +']';
		    ++i;
		}
	});
}

function enableState(countryId, stateId)
{
    var country = $(countryId);
    var state = $(stateId);
    if(country.options[country.selectedIndex].text == "United States")
        state.disabled= false;
    else
    {    
        state.selectedIndex = 0;
        state.disabled= true;
    }
}

var winHours = null;
function openHours(elem)
{
    var position = $(elem).cumulativeOffset();
    if(winHours == null)
    { 
        winHours = new Window
            ({className: "alphacube", 
            title: "Hours of Operation", 
            width:260, height:300, 
            destroyOnClose: false,
            recenterAuto:false,
			resizable: false,
			minimizable: false,
      		maximizable: false,
      		draggable: false,
      		zIndex: 1100,
      		showEffectOptions: {duration:0.1},
      		hideEffectOptions: {duration:0.1},
      		onClose: function() { setHours()}}
            );
        
        winHours.setContent('OpenHours');
    }
   
    winHours.setLocation(position[1] + 5, position[0]);
    if(IE6)
    {
        winHours.showCenter(); 
    }
    else
    {
        winHours.show(); 
    }
}



function fromvalueSelected(direction, id)
{
    var selectFrom = $('SelectFrom' + id);
    var selectTo = $('SelectTo' + id);
    if(direction == "from")
    {
        var select1 = selectFrom;
        var select2 = selectTo;
    }
    else
    {
        var select1 = selectTo;
        var select2 = selectFrom;
    }
    var val = select1.options[select1.selectedIndex].value;
    if(val == "Closed" || val == "Open24hrs")
    {
        select2.selectedIndex = 0;
        select2.disabled = true;
    }
    else
    {
        select2.disabled = false;
    } 
    
    if( selectFrom.selectedIndex >= selectTo.selectedIndex &&
       (selectFrom.selectedIndex != 0 && selectTo.selectedIndex != 0) )
    {
        select1.selectedIndex = 0;
    }   
}

var hoursArr = [];
var days = ["Mon. ", "Tue. ", "Wed. ", "Thu. ", "Fri. ", "Sat. ", "Sun. "];
function setHours()
{
    hoursArr = [];
    hoursArr.splice(0);
    var selects = $$('#OpenHours select');
    var list = $('DisplayHoursContainer');
    while(list.hasChildNodes()) list.removeChild(list.firstChild);
    var j = 0;
    for(var i = 0; i < selects.length; i += 2)
    {
        var from = selects[i].options[selects[i].selectedIndex].value; 
        var to = selects[i+1].options[selects[i+1].selectedIndex].value; 
        if((from == 0 || to == 0) && (from != "Open24hrs" && to != "Open24hrs"))
        {
            from = "Closed";
            to = "Closed";
        }
        var val = from + " - " + to;
        var valToInsert = "";
        if(selects[i].options[selects[i].selectedIndex].value == "Open24hrs" || selects[i+1].options[selects[i+1].selectedIndex].value == "Open24hrs")
        {
            valToInsert = "Open24hrs";
        }
        else if(selects[i].options[selects[i].selectedIndex].value == "Closed" || 
                selects[i+1].options[selects[i+1].selectedIndex].value == "Closed" ||
                selects[i].options[selects[i].selectedIndex].value == 0 || 
                selects[i+1].options[selects[i+1].selectedIndex].value == 0)
        {
            valToInsert = "Closed";
        }
        else
        {
            valToInsert = selects[i].options[selects[i].selectedIndex].text + " - " + selects[i+1].options[selects[i+1].selectedIndex].text;
        }
        new Insertion.Bottom(list, "<li><div class='first Left'>" + days[j++] + "</div><div class='Left'>" + valToInsert + "</div><div class='Break'></div></li>");
        hoursArr.push(val);
    }
    if(winHours != null)
    {
        winHours.hide(); 
    }
}

function validateHours(Error, type)
{
    var selects = $$('#OpenHours select');
    if(selects.length == 0)
    {
        return;
    }
    var valid = false;
    for(var i = 0; i < selects.length; i += 2)
    {
//        if( (selects[i].selectedIndex == 0 || selects[i+1].selectedIndex == 0) &&
//            (selects[i].options[selects[i].selectedIndex].value != "Open24hrs" && selects[i+1].options[selects[i+1].selectedIndex].value != "Open24hrs") &&
//            (selects[i].options[selects[i].selectedIndex].value != "Closed" && selects[i+1].options[selects[i+1].selectedIndex].value != "Closed")  
//          )
        if( selects[i].selectedIndex > 0 && selects[i+1].selectedIndex > 0 || 
            selects[i].options[selects[i].selectedIndex].value == "Open24hrs" || selects[i+1].options[selects[i+1].selectedIndex].value == "Open24hrs")
        {
            valid = true;
            break;
        }
    }
    var parent = $('InfoSupplierHoursContainer');
    if(!valid)
    {
        showErrorMsg(parent, "Please fill the hours of operation of your " + type);
        Error.found = true;
       
	    if(Error.elementToFocus == null)
	    {
	        var elementToFocus = $('expertWebsite');
	        if(elementToFocus == null)
	            elementToFocus = $('supplierWebsite')
	        Error.elementToFocus = elementToFocus;
	    }
    }
    else
    {
        hideErrorMsg(parent);
    }    
    
}

function resetHours()
{
    var selects = $$('#OpenHours select');
    for(var i = 0; i < selects.length; i++)
    {
        selects[i].selectedIndex = 0;
    }
}

function repeatDays()
{
    var selects = $$('#OpenHours select');
    var fromIndex = selects[0].selectedIndex;
    var toIndex = selects[1].selectedIndex;
    var disableFrom = selects[0].disabled == true;
    var disableTo = selects[1].disabled == true;
    for(var i = 2; i < 10; i += 2)
    {
        selects[i].selectedIndex = fromIndex;
        selects[i+1].selectedIndex = toIndex;
        selects[i].disabled = disableFrom;
        selects[i+1].disabled = disableTo;        
    }
}


function checkMaxChars(limit, elemId, infoElemId)
{
    var i = 0;
    var textarea = $(elemId);
    var infoElem = $(infoElemId);
    if(textarea)
    { 
        Event.observe(textarea, 'keypress', function(event)
            { 
                if(textarea.value.length <= limit)
                {
                    infoElem.innerHTML = "";
                }
                
                if(textarea.value.length >= limit)
                {
                    if( event.keyCode != Event.KEY_BACKSPACE && 
                        event.keyCode != Event.KEY_DELETE &&
                        event.keyCode != Event.KEY_LEFT &&
                        event.keyCode != Event.KEY_UP &&
                        event.keyCode != Event.KEY_RIGHT &&
                        event.keyCode != Event.KEY_DOWN &&
                        event.keyCode != Event.KEY_RETURN &&
                        event.keyCode != Event.KEY_ESC &&
                        event.keyCode != Event.KEY_RETURN &&
                        event.keyCode != Event.KEY_TAB &&
                        event.keyCode != Event.KEY_ESC &&
                        event.keyCode != Event.KEY_HOME &&
                        event.keyCode != Event.KEY_END &&
                        event.keyCode != Event.KEY_PAGEUP &&
                        event.keyCode != Event.KEY_PAGEDOWN)
                    {
                        infoElem.innerHTML = "You reached the limit";
                        Event.stop(event);
                    }
                }                
            });
    }
}

function setFlag(select, imgId)
{
//    var img = $(imgId);
//    var code = select.options[select.selectedIndex].getAttribute('xval');
//    if(code)
//    {
//        img.src = fullSiteRoot + "/Static/Images/Countries/" + code + ".gif";
//    }
//    else
//        img.src = fullSiteRoot + "/Static/Images/blank.gif";
}

Event.observe(window, "load", function(){checkMaxChars(1000, 'generalInfo', 'GeneralInfoCount') });
Event.observe(window, "load", function(){checkMaxChars(150, 'forumDescription', 'forumDescriptionCount') });
Event.observe(window, "load", function(){checkMaxChars(150, 'expertDescription', 'expertDescriptionCount') });