/*
######################################################################################################################
######################################################################################################################
							utils.js
######################################################################################################################
######################################################################################################################
*/

var Callbacks = {};
Callbacks.fire = function(key) {
  var fn = Callbacks[key];
  if (fn) {
    fn();
    Callbacks[key] = null;
  }
}

var domain = location.protocol + "//" + location.host;
var is_profile_edit_auto_complete_registered=null;
var is_img_auto_complete_registered = false;
var is_spell_check_done = false;
var is_redirection_done = false;
/*
    we are using this variable in validate_geo_location method to skip validation if required.
*/
var firstLoad = true;

var is_vid_auto_complete_registered = false;
var is_blog_auto_complete_registered = false;


var is_verify_geolocation = true;
var is_disable_img_button = false;



function periodicalUpdater() {
	new Ajax.Request('/twitter/cb_tweets', {
			parameters:"",
			asynchronous:false,
			onComplete: function(transport) {
				$('listOfTweets').insert({ top: transport.responseText });
				setTimeout(periodicalUpdater, 7000);
			}
        });
}
function periodicalUpdaterIncoming() {
	new Ajax.Request('/twitter/cb_incoming_tweets', {
			parameters:"",
			asynchronous:false,
			onComplete: function(transport) {
				$('listOfTweets').insert({ top: transport.responseText });
				setTimeout(periodicalUpdaterIncoming, 7000);
			}
        });
}

function showBox(box){
	try
    {
        //hide all boxes
        if($('popupRegisterBox'))
        {
           $('popupRegisterBox').hide();
        }
        if($('popupActivationBox'))
        {
            $('popupActivationBox').hide();
        }
        if($('popupLoginBox'))
        {
            $('popupLoginBox').hide();
        }
        if($('popupResendActivationEmailBox'))
        {
            $('popupResendActivationEmailBox').hide();
        }
        if($('popupForgotPasswordBox'))
        {
            $('popupForgotPasswordBox').hide();
        }
        if($('popupListContactsBox'))
        {
            $('popupListContactsBox').hide();
        }
        if($('popupThanksForInvitingContactsBox'))
        {
            $('popupThanksForInvitingContactsBox').hide();
        }
        if($('popupCalculatorContainer'))
        {
            $('popupCalculatorContainer').hide();
        }
        if($('popupRedeemPoints'))
        {
            $('popupRedeemPoints').hide();
        }
        if($('popupFacebookConnectCreateAccount'))
        {
            $('popupFacebookConnectCreateAccount').hide();
        }
        //show the right box
        if (box != null && box) {
            box.show();

        }
    }catch(ex)
    {
        log_exceptions(" Method: - showBox " + ex.message);
    }
}
function setFocusAndClearErrorMessage(focusElement, errMsgElement) {
    focusElement.focus();
    errMsgElement.innerHTML = '';
}

function loadBox(){
	var box = readCookie('show_box');
	if (box != null && box == "registration_box") {
		showRegisterBox($('joinAllvoices'));
	}	else if (box != null && box == "login_box") {
		showLoginBox($('loginAllvoices'));
	} else if (typeof(box) != "undefined" && box != null && box != "") {
	  new Ajax.Request('/user/show_post_login_popup', {parameters:"popup_name="+box,asynchronous:false});
	}

	setCookie('show_box', "");
}


function moveTwitterPopupBox(){
	movePopupBox($('popupTwitterCompleteBox'), $('addTwitterCredentials'));
}
var clickedPopupButton = "";
function movePopupBox(box, button) {
    try
    {
        // reset the positioning var
        //if(button == "top") {
        //    clickedPopupButton = "";
        // }

        // we need to track the starting point of the click if it's a button click
        if(button) {
            clickedPopupButton = button;
        } else if(clickedPopupButton != "") {
            button = clickedPopupButton;
        }

        // remove any specific arrow class settings
        classNames = box.className.split(" ");
        box.className = "";
        for(i = 0; i < classNames.length; i++) {
            if(classNames[i].substr(0,10) != "popupArrow") {
                box.className += " " + classNames[i];
            }
        }

        if(button) {

            var top = "";
            var right = "";
            var bottom = "";
            var left = "";
            var coords = SpareTools.getOffsetFromWrapper(button);  // get coords of button or link clicked

            // find box and arrow coords
            if(button.innerHTML == 'Login') {
                top = 35;
                right = 1008 - coords['x'] - 291;
                box.className += " popupArrowLoginTop";
            } else if(button.innerHTML == 'Join Allvoices') {
                top = 35;
                right = 1008 - coords['x'] - 256;
                box.className += " popupArrowRegisterTop";
            } else if(button.id == 'report_your_news_top') {
                top = 42;
                right = 5;
                box.className += " popupArrowNewsTop";
            } else if(button.id == 'report_your_news_right') {
                top = coords['y']+40;
                right = 5;
                box.className += " popupArrowNewsRight";
            } else if(button.id == 'report_your_news_left') {
                top = coords['y']+40;
                right = 615;
                box.className += " popupArrowNewsLeft";
            } else if(button.id == 'postcomment') {
                top = coords['y']+40;
                right = 600 - coords['x'];
                box.className += " popupArrowComments";
            } else if(button.id == 'twitterFormLink') {
                top = coords['y']+25;
                left = coords['x']-5;
            } else if(button.className == 'addPlus') {
                top = coords['y']+25;
                right = 1008 - coords['x'] - (button.offsetWidth / 2) - 65;
                box.className += " popupArrowAddPlus";
			} else if(button.id == 'showCalculator') {
                top = 40;
                right = 5;
                box.className += " popupArrowNewsTop";
			} else if(button.id == 'showRedeemPoints') {
                top = 40;
                right = 105;
                box.className += " popupArrowNewsTop";
			} else if(button.id == 'inviteMoreContacts') {
                top = 35;
                right = 110;
            } else if(button.parentNode.className == 'links') {
                top = coords['y']+25;

                if(button.parentNode.parentNode.parentNode.parentNode.parentNode.className == 'left') {
                    right = 1008 - coords['x'] - (button.offsetWidth / 2) - 310;
                    box.className += " popupArrowAddPlusLeft";
                } else {
                    right = 1008 - coords['x'] - (button.offsetWidth / 2) - 70;
                    box.className += " popupArrowAddPlus";                    
                }
                

            } else {
                top = coords['y']+40;
                left = coords['x']-30;
            }

            // move box to the coords
            SpareTools.moveObject(box, top, left, bottom, right);

        } else {
            box.style.left = "";
            box.style.top = "";
        }
    }catch(ex)
    {
        log_exceptions(" Method: - movePopupBox " + ex.message);
    }
}

function saveComments(moveActivationBox) {
	//alert(" in save comments ");
	if ($('save_comment') != null && typeof($('save_comment')) != "undefined" && $('save_comment').value == "true") {
	  $('save_comment').value = "false";
	  
	  var epId = "";
	  
	  var aForm = document.getElementById("comment_for_event_person");
	  for (var i=0;i<aForm.length;i++) {
	  	if ( aForm.elements[i].name == "event_person_id") {
				epId = aForm.elements[i].value;
			}
	  }
  	
  	if (epId == null || epId == "") {
  		epId = $('event_person_id').value;
  	}
  	
  	//alert ("in save comments , event_person_id " + epId);
  
		submit_comment_form(epId);
		if (moveActivationBox) {
			movePopupBox($('popupActivationBox'), $('postcomment'));
		}
	}
}

function showResendActivationEmailBox(button) {
    box_id = "popupResendActivationEmailBox";
    evalStr = 'setFocusAndClearErrorMessage($(\'popup_resend_username\'), $(\'resendActivationEmailErrorMessage\'))'
	get_box('resend', box_id, evalStr);
    showBox($(box_id));
    movePopupBox($(box_id), button);
}
function showForgotPasswordBox(button) {
    box_id = "popupForgotPasswordBox";
    evalStr = 'setFocusAndClearErrorMessage($(\'popup_forgot_username\'), $(\'forgotPasswordErrorMessage\'))';
	get_box('forgot', box_id, evalStr);
    showBox($(box_id));
    movePopupBox($(box_id), button);
}
function showLoginBox(button, callback) {
	//check if logged in and redirect if necessary
	if (is_logged_in()) {
		saveComments(false);		// check if necessary is being done in the
		if ($('redirectUrl') != null && typeof($('redirectUrl')) != "undefined" && $('redirectUrl').value != '') {
			window.location.href=$('redirectUrl').value;
			return true;
		}
	}
    box_id = "popupLoginBox";
    evalStr = 'setFocusAndClearErrorMessage($(\'popup_login_username\'), $(\'loginErrorMessage\'))';
    get_box('login', box_id, evalStr);
    showBox($(box_id));
    movePopupBox($(box_id), button);
    if (callback) Callbacks.postLogin = callback;
}
function showRegisterBox(button) {
    try{
        box_id = "popupRegisterBox";
        remove_all_decendants('change_captcha_register');
        evalStr = 'setFocusAndClearErrorMessage($(\'popup_user_email\'), $(\'registerErrorMessage\'))' + ";create_recaptcha('change_captcha_register');";
        //change_captcha_register
        get_box('register', box_id, evalStr);
        showBox($(box_id));
        movePopupBox($(box_id), button);
    }catch(ex)
    {
        log_exceptions(" Method: - showRegisterBox " + ex.message);
    }
}
function showTwitterBox(button) {
    box_id = "popupTwitterBox";
    evalStr = 'setFocusAndClearErrorMessage($(\'popup_user_email\'), $(\'twitterErrorMessage\'))';
    get_box('twitter', box_id, evalStr);
    showBox($(box_id));
    movePopupBox($(box_id), button);
}
function setTwitterName(user_name){
	$('twitter_name').innerHTML = 'Your Twitter credentials are set to <a href="http://www.twitter.com/'+user_name+'" target="_blank">'+user_name+'</a>.';
	$('twitter_credentials').innerHTML = 'We have already have your Twitter credentials.';
}
function showTwitterCompleteBox(button, str) {
    box_id = "popupTwitterCompleteBox";
    get_box('twitter_complete', box_id, str);
	showBox($(box_id));
    movePopupBox($(box_id), button);
}
function showActivationBox(button) {
    box_id = "popupActivationBox";
    showBox($(box_id));
    movePopupBox($(box_id), button);
}

/*function showFacebookConnectBox(button, user_name) {
    facebooker_debugger('showFacebookConnectBox');
    box_id = "popupFacebookConnectCreateAccount";
	evalStr = '$(\'popup_user_name_fb\').value=\''+user_name+'\'';
    get_box('facebook_connect', box_id, evalStr);
	showBox($(box_id));
    movePopupBox($(box_id), button);
}*/
function resetRedirectUrl() {
	if ($('redirectUrl') != null && typeof($('redirectUrl')) != "undefined") {
		$('redirectUrl').value='';
	}
}
function redirectUrl(url){
	if (url == '') { // if url is empty try getting it from redirectUrl input field
		if ($('redirectUrl') != null && typeof($('redirectUrl')) != "undefined" && $('redirectUrl').value != '') {
			url = $('redirectUrl').value;
		}
	}

	if (url != '')
    {
		window.location.href=url;
	}

	return;
}
function postAuthenticationProcess(moveActivationBox, user_id) {
	//alert (" in postAuthenticationProcess ");
	if ($('redirectUrl') != null && typeof($('redirectUrl')) != "undefined" && $('redirectUrl').value != '') {
		//if (window.opener != null) {
			window.location=$('redirectUrl').value;
      is_redirection_done = true;
		//}
	}
	if ($('loggedIn') != null && typeof($('loggedIn')) != "undefined") {
		$('loggedIn').value = user_id;
	}
	
	Callbacks.fire('postLogin');
	saveComments(moveActivationBox);
}

function reloadPage() {
    if(!is_redirection_done)
    {
      doReloadPage.defer();
    }
    is_redirection_done = false;
}

function doReloadPage() {
  window.location.reload();
}

function inviteContacts(shouldInvite) {
	if (shouldInvite == "true") {
		box_id = "popupListContactsBox";
		showBox($(box_id));
	}// else {
	//	box_id = "popupActivationBox";
	//	showBox($(box_id));
	//}

	return false;
}


/* #########################################################################################################
                    FUNCTIONS FOR VALIDATING COUNTRY,STATE,CITY
                    AUTO-COMPLETION OF COUNTRY,STATE,CITY
######################################################################################################### */

/*
    function used to validate state
*/
function validate_state(state_name,country, element_to_show,progress_element) {
    //alert(city_name);
    url = domain + "/main/cb_check_state";
    if ($(element_to_show) != null) {
        Element.hide(element_to_show);
    }
    if ($(progress_element) != null ) {
        Element.hide(progress_element);
    }
    //Element.hide(progress_element);
    if (state_name == "" || country == "") {
        return;
    }
    getVars = "state=" + state_name + "&country="+country;
    on_complete_method = function(transport){
        response_data = eval(transport.responseText);
        if (typeof progress_element != 'undefined') {
            Element.hide(progress_element);
        }
        if ( response_data.status == "cancel" ) {
            Element.show(element_to_show);
        } else {
            /*event_city = $('event_city');
                            if (event_city  != null) {
                                event_city.disabled = false;
                                if (event_city.value == "") {
                                    event_city.focus();
                                }
                            }*/
            Element.hide(element_to_show);
        }
    };
    new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
                                onLoading:function() {
                                    if (typeof progress_element != 'undefined') {
                                        Element.Show(progress_element);
                                    }
                                },
                                onComplete: on_complete_method
                               });
}


/*
    function used to validate city
*/
function validate_city(city_name,country, element_to_show,progress_element,state_value) {
    //alert(city_name);
    url = domain + "/main/cb_check_city";
    Element.hide(element_to_show);
    if ($(progress_element) != null ) {
        Element.hide(progress_element);
    }
    Element.hide(progress_element);
    if (city_name == "" || country == "") {
        return;
    }

    getVars = "city=" + city_name + "&country="+country;
    /*if ($('event_state') != null) {
        getVars += "&state=" + $('event_state').value;
    }*/
    if (typeof(state_value)!= 'undefined' &&  state_value != '') {
        getVars += "&state=" + state_value;
    }

    on_complete_method = function(transport) {
        response_data = eval(transport.responseText);
        if (typeof progress_element != 'undefined') {
            Element.hide(progress_element);
        }
        if ( response_data.status == "cancel" ) {
            Element.show(element_to_show);
        } else {
            Element.hide(element_to_show);
        }
    };
    new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
                                onLoading:function() {
                                    if (typeof progress_element != 'undefined') {
                                        Element.Show(progress_element);
                                    }
                                },
                                onComplete: on_complete_method
                               });
}
/*
    function for validating country.
*/
function validate_country(country_name, element_to_show,progress_element) {
    url = domain + "/main/cb_check_country";
    if (country_name == "") {
        return;
    }
    //alert(element_to_show);
    //Element.hide(element_to_show);
    getVars = "country="+country_name;

    new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
                                onLoading:function() {
                                    if (typeof progress_element != 'undefined') {
                                        Element.show(progress_element);
                                    }
                                },
                                onComplete: function(transport){
                                    response_data = eval(transport.responseText);

                                    if (typeof progress_element != 'undefined') {
                                        Element.hide(progress_element);
                                    }
                                    //alert(response_data.status)
                                    if ( response_data.status == "cancel" ) {
                                        Element.show(element_to_show);
                                    } else {

                                        Element.hide(element_to_show);

                                      temp_element = $('user_cellphones_country_code');

                                        if (typeof temp_element != 'undefined' ) {
                                          temp_element.value = response_data.country_code;
                                        }
                                    }
                                }
                               }
                    );
}

/*
    this function is used for loading cities of selected country in the list
*/
function onChangeCountry(objSelect) {
  var countryname;
    countryname = objSelect.options[objSelect.selectedIndex].value;
    cityselect = $("geolocation_id");
    cityselect.disabled = true;

    //$('loadingmsg').style = "";
  showhidediv('hidediv','showdiv');
    //$('loadingmsg').
    //initiate ajax call to load cities relevant to country
    new Ajax.Request("/main/cb_getcities", {parameters:{"country":countryname}, asynchronous:true,onLoading:function(){
        /*displaying progress bar*/
    }//end onLoading function
                                            ,onComplete: function(transport){
                                                try
                                                {
                                                    json_data = eval(transport.responseText);
                                                    cityselect.clear();
                                                    cityselect.length = 0;

                                                    for( i=0; i<json_data.length; i++ ) {
                                                        var y=document.createElement('option');
                                                        y.text = json_data[i].attributes.location_name;
                                                        y.value = json_data[i].attributes.id;
                                                        try
                                                        {
                                                            cityselect.add(y,null); // standards compliant
                                                        }
                                                        catch(ex) {
                                                            cityselect.add(y); // IE only
                                                        }
                                                    }
                                                }catch(ex) {
                                                    log_exceptions(" callback: - onComplete of cb_getcities " + ex.message);
                                                }
                                                cityselect.disabled = false;
                                              showhidediv('showdiv','hidediv');
                                            } //end Complete function
                                           } //end parameters
                    );
}

function register_geo_location_with_id_new(i, fields_prefix, offsetLeft, inputLocation) {
    fields_prefix = (fields_prefix || "");
    inputLocation = (inputLocation || "");

    var clear = function () {
        $(fields_prefix + "geo_no_city_" + i).hide();
        $(fields_prefix + "geo_city_wait_" + i).hide();
    }
    var loading = function() {
        var parameters = "";
        if($(fields_prefix + "geo_country_" + i).selectedIndex) {
            $(fields_prefix + "geo_no_city_" + i).hide();
            $(fields_prefix + "geo_city_wait_" + i).show();
            var country = "&country_hint=" + $(fields_prefix + "geo_country_" + i).options[$(fields_prefix + "geo_country_" + i).selectedIndex].innerHTML;
            if($(fields_prefix + "state_field_geo_" + i).style.display != "none") {
                var state = "&state=" + $(fields_prefix + "geo_state_" + i).value;
            } else {
                var state = "";
            }
            var city = "&city_hint=" + $(fields_prefix + "geo_city_" + i).value.replace(/^\s+|\s+$/g, '');  // replace trims whitspace
            var parameters = city + country + state;
        }
        return { action:'/main/cb_city_auto_complete', parameters: parameters};
    }
    var done = function() {
        $(fields_prefix + "geo_city_wait_" + i).hide();
    }
    var none = function() {
        $(fields_prefix + "geo_city_wait_" + i).hide();
        $(fields_prefix + "geo_no_city_" + i).show();
    }
    //console.log("register_geo_location_with_id_new --> loading method output::: ");
    //console.log(loading());
    //if parameter changed then just refresh the autocomplete.
    new AutoComplete(fields_prefix + 'geo_city_' + i,
                {inputLocation: inputLocation, clearFunc: clear, loadFunc: loading, doneFunc: done, noneFunc: none, offsetLeft: offsetLeft, delay: 0.25, resultFormat: AutoComplete.Options.RESULT_FORMAT_HTML });
}

/*
    This autocomplete used for auto-completion filed of country,state and city.
*/
function register_geo_location_with_id(i, prefix, prefill_siblings) {
  var fields_prefix = "";
    if (typeof(prefix) != "undefined") {
        fields_prefix = prefix;
    }
  var shared_image_city_1_auto_completer = new Ajax.Autocompleter(
    fields_prefix + "geo_city_"+i,
    fields_prefix +"geo_city_list_auto_complete_"+i,
    '/main/cb_city_auto_complete',
    {
      callback:function(element, value) {
        try{
          Element.hide(fields_prefix +'geo_no_city_'+i);
          return '?country_hint=' + $(fields_prefix +'geo_country_'+i).options[$(fields_prefix +'geo_country_'+i).selectedIndex].text +'&state='+$(fields_prefix +'geo_state_'+i).options[$(fields_prefix +'geo_state_'+i).selectedIndex].text +'&city_hint='+$(fields_prefix +'geo_city_'+i).value;
        }catch(ee){
          log_exceptions(" callback: - Ajax.Autocompleter callback " + ee.message);
          return false;
        }
      },
      minChars:1,
      indicator:fields_prefix+"geo_city_wait_"+i,
      updateElement:function(element) {
        var inputel =  $(fields_prefix + "geo_city_"+i);
        inputel.value=element.innerHTML;

        // in cases where there are multiple location inputs in a form, this is a convenience to prefill empty "siblings"
        if (prefill_siblings) {
          prefill_form_fields(inputel.form, fields_prefix+'geo_city_', inputel);
        }
      }
    }
  );
}

/*###################################################################################################################
            END OF FUNCTIONS RELATED WITH VALIDATING COUNTRY,STATE,CITY & AUTO-COMPLETION OF COUNTRY,STATE,CITY
################################################################################################################### */
/*
    This function is used to clear fields on table etc.
    In case if there is form then we can clear all fields by calling its reset method.
*/
function do_fields_empty(field_list) {
    for(i=0; i<field_list.length; i++) {
        $(field_list[i]).value = '';
    }
}

/*
    method used in tab selection
*/
function tab_selection(cur_tab,cur_a,other_tab,other_a,selection_class) {
    try
    {
        log_exceptions("other tab ::: " + typeof(other_tab));
        for(var i=0;i<other_tab.length;i++) {
            try
            {
                hideDiv(other_tab[i]);
            } catch (e) {
                log_exceptions("Method: - tab_selection catch block 1 " + e.message);
            }
        }
        showDiv(cur_tab);
        if (typeof other_a == "object") {
            for(var i=0;i<other_a.length;i++) {
                try
                {
                    if ($(other_a[i]).hasClassName(selection_class)) {
                      $(other_a[i]).removeClassName(selection_class);
                    }
                } catch(e){
                    log_exceptions("Method: - tab_selection catch block 2 " + e.message);
                }
            }
        } else {
            if ($(other_a).hasClassName(selection_class)) {
                $(other_a).removeClassName(selection_class);
            }
        }
        if (!$(cur_a).hasClassName(selection_class)) {
            $(cur_a).addClassName(selection_class);
            $(cur_a).blur();
        }
    }catch(ex) {
        log_exceptions("Method: - tab_selection catch block 3 " + ex.message);
    }
}

function change_tab_selection(cur_tab,cur_a,other_tab,other_a,selection_class) {
    tab_selection(cur_tab,cur_a,other_tab,other_a,selection_class);
}

function showDiv(id) {
    Element.show(id);
}
function hideDiv(id) {
    Element.hide(id);
}
/*
    this function is used to check the user name
*/
function checkusername(usernamefield,statusfield,previouse_name) {
    try
    {
      var newusername = $(usernamefield).value.strip().replace(/[^a-zA-Z0-9\-\.\_]+/, '');
      newusername = newusername.replace(/[;.]+/g, '');
      $(usernamefield).value = newusername;
     
        if (typeof previouse_name != 'undefined') {
            if (previouse_name == newusername) {
                $(statusfield).update("");
                return false;
            }
        }
        if ( newusername == "" ){
            //alert("Please first give username");
            return false;
        }

        if (newusername.length < 5) {
            $(statusfield).update("<font color=RED><b>" + error_list.username_min_length  + "</b></font>");
            return false;
        } else if (newusername.length > 255) {
            $(statusfield).update("<font color=RED><b>" + error_list.username_max_length  + "</b></font>");
            return false;
        }

        $(usernamefield).disabled = true;

        //initiate ajax call to load cities relevant to country
        new Ajax.Request("/user/check_existing_user", 
                         {
                          parameters:{"username":newusername},
                          asynchronous:true,
                          onLoading:function(){},
                          onComplete: function(transport){
                                 var isexisted= parseInt(transport.responseText);
                                 $(usernamefield).disabled = false;
                                 if (isexisted == 1) {
                                     $(statusfield).innerHTML = "<font color=GREEN><b>" + error_list.signup_username_free + "</b></font>";
                                 } else if (isexisted == 0) {
                                     $(statusfield).innerHTML = "<font color=RED><b>" +  error_list.signup_username_unavailable + "</b></font>";
                                 }
                                 
                             } //end Complete function
                         }
                        );
    } catch(ex) {
        log_exceptions("Method:- checkusername " + ex.message);
    }
}

/*hide element if its shown*/
function hide_element_shown(element_name) {
    if ($(element_name).visible()) {
        Element.hide(element_name);
    }
}

/*
    clear element list
*/
function clear_txt_fields(elementlist) {
    for(i=0; i<elementlist.length; i++) {
        $(elementlist[i]).value= "";
    }
}
/*for disable and enabling elements list*/
function change_status_elements(elementlist, status) {
    for(i=0; i<elementlist.length; i++) {
        $(elementlist[i]).disabled = status;
    }
}
/*Remove previous error div as Erevent_location_editror Div name is common at all places so far to display error.*/
function remove_previous_error_div(postfix) {
    if ( typeof(postfix) == 'undefined' ) {
        postfix = '';
    }
    if ($('errorExplanation'+postfix)) //removing previous displayed div
    {
        Element.remove('errorExplanation'+postfix);
    }else if($('errorList'+postfix))
	{
        Element.remove('errorList'+postfix);

	}

}
//    This method is used for changing category on event page, index page and also used at login & signup page
//    in anchor with href for going on the category page.
function change_category(cat){
    /*
        json_data is defined in json file, contains information about widgets but for some pages there is no need of it like signup
        and login pages but we are using this method. For making this methods generic for all page we are checking if its 'undefined'
        then simply exit the function.
    */
  document.title="Business";
    if ( typeof(json_data) == "undefined" ) {
        return;
    }
}
function showhidediv(classtoremove,classtoadd) {
    if ( $('loadingmsg').hasClassName(classtoremove) ) {
        $('loadingmsg').removeClassName(classtoremove);
      $('loadingmsg').addClassName(classtoadd);
    }
}
/*This function is used to hide visible elements*/
function make_visible_elmnt_hide(element_name) {
    if (typeof element_name != "undefined") {
        if (Element.visible(element_name)) {
            new Effect.Fade(element_name, {duration: 1.0});
            //new Effect.Highlight(elementid, {startcolor: '#dddddd', delayed: 0.5, duration: 2.0});
            //Element.hide(element_name);
        }
    }
}
/*
    Remove status message div
*/
function status_message_div() {
    if ($('status_message') == null) {
        return;
    }
    if ($('status_message').visible()) {
        Element.remove('status_message');
    }
}



/*
######################################################################################################################
######################################################################################################################
                            forms_validation.js
######################################################################################################################
######################################################################################################################
*/
/* validate_prov
    This method is used to validate the answer,question and comments
    Parameters :
                element_to_check=element name whose value to be checked
                div_to_add = In which we need to add Error Explanation div
                title = text like Question,Answer and comment
*/
function validate_comment_temp() {
    try{
        var res_val_field1 = validate_empty_field('content_comment_comment','div_comment_form','Comment','370px');
        setCookie('editornew',$('abc').value);
        //alert(typeof(res_val_field1));
        if ($('abc').value=='edit')RedBox.close();
    }catch(e) {
        log_exceptions("Method :- validate_comment_temp " + e.message);
    }
    return res_val_field1;
}

var abc=0;

function validate_empty_field(element_to_check,div_to_add,title,optional_width,is_tiny_mce) {
	//disable_form(div_to_add, true);
    var errorhtml = "";

    remove_previous_error_div();
    if(typeof(is_tiny_mce) != 'undefined')
	{
		var my_values = get_tiny_mce_value(element_to_check);

		if(typeof(my_values) != "object")
		{
			return false;
		}

		if ( my_values.text_value == '' || my_values.is_empty == true )
		{
        	errorhtml += "You must write something.#";
    	}
	}
	else
	{
		if ( $(element_to_check).value.strip() == "")
		{
        	errorhtml += "You must write something.#";
    	}
	}

    if (errorhtml == "") {
        //disable_form(div_to_add);
        return true; //in case of successful validation
    } else {
        style = '';
        if (typeof optional_width != "undefined" && optional_width!='') {
            style = optional_width;
        }

        new Insertion.Top(div_to_add,get_error_list_html(errorhtml.split("#"),"error(s) prohibited this " + title.toLowerCase() + " from being saved"));
		//disable_form(div_to_add, false);
        return false;
    }
}

function validate_empty_textarea(element_to_check,div_to_add,title,optional_width) {
	//disable_form(div_to_add, true);
    var errorhtml = "";

    remove_previous_error_div();

	if ( trim($(element_to_check).value).length == 0 )
	{
    	errorhtml += "You must write something.#";
	}

    if (errorhtml == "") {
        return true; //in case of successful validation
    } else {
        style = '';
        if (typeof optional_width != "undefined" && optional_width!='') {
            style = optional_width;
        }

        new Insertion.Top(div_to_add,get_error_list_html(errorhtml.split("#"),"error(s) prohibited this " + title.toLowerCase() + " from being saved"));
		return false;
    }
}


/*
    this function is used for changing elment's id contained in sending element.
    In safari get confuse when there are two variable in the dom.
    More detail::In Safari, if you want to modify elements in the redbox (e.g. disable/enable a submit button based on the value of a checkbox), you must, it appears, hack redbox.js to give the elements of which clones were made for the redbox different ids. Otherwise Safari gets confused about which element to modify. To see what I mean, look at the hack:
    For more info :: http://blog.craigambrose.com/past/2006/9/22/redbox-release-2/#c556
*/
function add_postfix(node) {
    parent_elmnt = $(node);
    child_element = parent_elmnt.descendants();
  parent_elmnt.id += "_old";
    log_exceptions("add postfix :: "  + parent_elmnt.id);

    for(i=0; i<child_element.length; i++) {
        if (typeof(child_element[i].id) != 'undefined') {
            if (child_element[i].id != null && child_element[i].id != "") {
                log_exceptions('Element name :: ' + child_element[i].name);
                child_element[i].id += "_old";
                log_exceptions(child_element[i].id);
            }
        }
    }
    log_exceptions('==================================');
}

/* remove _old from ids to use div again*/
function remove_postfix(node) {
    parent_elmnt = $(node);
    child_element = parent_elmnt.descendants();
    parent_elmnt.id = parent_elmnt.id.sub('_old','');
    log_exceptions(parent_elmnt.id);
    for(i=0; i<child_element.length; i++) {
        if (typeof(child_element[i].id) != 'undefined') {
            if (child_element[i].id != null && child_element[i].id != "") {
                child_element[i].id = child_element[i].id.sub('_old','');
                log_exceptions(child_element[i].id);
            }
        }
    }

}


/*
    This method is used to validate the answer, question and comments
    Parameters :
                element_to_check=element name whose value to be check
                div_to_add = In which we need to add Error Explanation div
                title = text like Question,Answer and comment
*/
function validate_multiple_empty_field(element_to_check,div_to_add,title,optional_width) {
    disable_form(div_to_add,true);
    var errorhtml = "";

    remove_previous_error_div();
    for(var i=0;i<element_to_check.length;i++) {
        if ( $(element_to_check[i]).value == "") {
            errorhtml += title[i]+" can't be empty.#";
        } else {
            if ($(element_to_check[i]).value.length > 0 && $(element_to_check[i]).value[0]==' ') {
                errorhtml += "Text should not start with space#";
            }
        }
        // check for image ext
        if (element_to_check[i] == 'shared_image_1') {
          temp = $F(element_to_check[i]);
            if ( (temp != "")  && (!checkExtension_img(temp))  ) {
                errorhtml +=  error_list.unknown_img_format + "#"; //"File format not supported#";
            }
        }
        //end of image ext check
        // check for video ext
        if (element_to_check[i] == 'shared_video_1'){
          temp = $F(element_to_check[i]);
            if ( (temp != "")  && (!checkExtension_vid(temp))  )    {
                errorhtml += error_list.unsupported_format + "#";
            }
        }
        //end of video ext check
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        var style = '';
        if (typeof optional_width != "undefined") {
          style = optional_width;
        }
        new Insertion.Top(div_to_add,get_error_div(errorhtml.split("#"),"error(s) prohibited this form from being saved",style,'errorExplanation_ans'));
        disable_form(div_to_add,false);
        return false;
    }

}

/*
    This method is used to validate the form fields on forgot password page
*/
function validate_forgot_form() {
    disable_form('login_content',true);
    var errorhtml = "";
    remove_previous_error_div();
    if ($('user_email').value == "") {
        errorhtml += error_list.forgot_blank_email + "#";
    } else if ( !validateemail($("user_email").value) ) {
        //errorhtml += "<li>Please enter correct email address</li>";
        errorhtml +=  error_list.wrong_email + "#";
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top('login_content',get_error_list_html(errorhtml.split("#"),error_list.forgot_password_error_heading,''));
        disable_form('login_content',false);
        return false;
    }
}

/*
    This method is used to validate the blogs on event and people_in_the_new
*/
function validate_blog_form() {
    disable_form('display_error',true);
    var errorhtml    = "";

    remove_previous_error_div();
    if ( $("blog_title").value == "" ) {
        errorhtml += error_list.blank_title + "#";
    }

    if (tinyMCE.get('blog_full_content').getContent()=='') {
        errorhtml += error_list.blank_body + "#";
    }

    if ( $F("shared_blog_country_1") != "" ) {
        validate_country($F("shared_blog_country_1"),'blog_no_country','blog_country_wait');
        if (Element.visible('blog_no_country')) {
            errorhtml += error_list.country_not_found + "#";
        }
    }

    if ( $F("shared_blog_city_1") != "" ) {
      validate_city($F("shared_blog_city_1"),$F("shared_blog_country_1"),'blog_no_city','blog_city_wait');
        if (Element.visible('blog_no_city')) {
            errorhtml += error_list.city_not_found + "#";
        }
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top('display_error',get_error_div(errorhtml.split("#"),error_list.blogs_error_heading,''));
        disable_form('display_error',false);
        return false;
    }
}

/*
This method is used for finding whether value of tiny_mce-textbox is empty or not.
Problem was due to tiny_mce editor stuff in safari as its triggersave method was not working proper. I also tried tiny_mce online
examples of 3.05 but triggersave method was also not working properly there and was giving some html tag in case of empty textbox.

If we press 7 times spacebar key in textbox and then we check its lengh its gives 7 but after stripping(removing space around text) it again gives lenght 7 and this is wrong behaviour and this case is only with safari.In this method we are checking the ascii codes
of the given text and then return true | false depending the no_of_matches character and length. I have also added a method in tiny_mce.js file above getContent method. For reference i'm copying it here.

//modification for allvoices
gettextContent:function(o){try{var t=this,h;if (typeof(t.getBody().innerText)=='undefined'){h=t.getBody().textContent;}else {h=t.getBody().innerText;};return h;}catch(ex){alert(ex.message);}}

http://www.geocities.com/Athens/Academy/4038/graph/fontset.htm
http://www.asciitable.com/

If we have lot of spaces,line feeds and Carriage Return in given text then it will given false.

*/

my_tiny_mce_object = function(){
    this.is_empty = false;
    this.text_value  = '';
}

function get_tinymce_textbox_value() {
    //alert('checking space code');
    textContent = tinyMCE.activeEditor.gettextContent();
    if (typeof(textContent) == 'undefined') {
        textContent = '';
    }
    no_of_matches = 0;
    for(i=0;i<textContent.length;i++) {
        current_code = textContent.charCodeAt(i);
        if (current_code == 160 || (current_code >=0 && current_code <=32) ) {
            no_of_matches += 1;
        } else {
            break;
        }
    }

    if (no_of_matches == textContent.length) {
        return true;
    } else {
        return false;
    }

}
/*
	this function used to get the value from tinymce
*/
function get_tiny_mce_value(txtarea_elem,use_get_content) {
	try
	{
		my_values = new my_tiny_mce_object();
		if (typeof(use_get_content) == 'undefined') {
			$(txtarea_elem).value = tinyMCE.activeEditor.getContent();
		} else {
			$(txtarea_elem).value = tinyMCE.get(txtarea_elem).getContent();
		}
		my_values.text_value = $(txtarea_elem).value.strip();
		if (my_values.text_value  != '') {
			my_values.is_empty = get_tinymce_textbox_value();
		}
		return my_values;
	}catch(ex)
	{
		log_exceptions("Method :- get_tiny_mce_value " + ex.message);
        return false;
	}
}
function validate_blog_form_in_lb() {
    var my_values = get_tiny_mce_value('blog_full_content');

	if(typeof(my_values) != "object")
	{
		return false;
	}

	disable_form('edit_blog_form',true);
    var errorhtml    = "";
    remove_previous_error_div();

    if ( $("blog_title").value == "" ) {
        errorhtml += error_list.blank_blog_title + "#";
    }

    if ( my_values.text_value == '' || my_values.is_empty == true ) {
        errorhtml += error_list.blank_body + "#";
    }

    //errorhtml += validate_geo_location('','optional');


    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        disable_form('div_blog_edit_form',false);
        new Insertion.Top('div_blog_edit_form',get_error_div(errorhtml.split("#"),error_list.blogs_error_heading,''));
        return false;
    }
}
// JavaScript Document
/*
    This function is central for settings geolocation
*/
function validate_geo_location(prefix,is_compulsory,postfix,previous_country,previous_city,previous_state) {

    /*we are checking this variable as at some places like */
    if (!is_verify_geolocation) {
        return '';
    }

    if (typeof(postfix) == 'undefined') {
        postfix = 1;
    }

    var fields_prefix = "";
    var required = true;
    remove_previous_error_div();

	if(typeof(previous_country) == 'undefined')
	{
		previous_country = '';
	}

	if(typeof(previous_city) == 'undefined')
	{
		previous_city = '';
	}


	if(typeof(previous_state) == 'undefined')
	{
		previous_state = '';
	}


    if (typeof(prefix) != "undefined") {
        fields_prefix = prefix;
    }




    if (typeof(is_compulsory) != "undefined") {
        if (is_compulsory == 'optional') {
            required = false;
        }
    }

    var country_value=$(fields_prefix+"geo_country_" + postfix).options[$(fields_prefix+"geo_country_" + postfix).selectedIndex].value;
    var is_country = ($(fields_prefix+"geo_country_" + postfix).selectedIndex != -1 && $(fields_prefix+"geo_country_" + postfix).selectedIndex != 0);
    var is_state = false;
    var state_value = '';
	var city_value = $(fields_prefix+"geo_city_" + postfix ).value;

    if (is_country && country_value=='United States of America') {
        is_state = ($(fields_prefix+"geo_state_" + postfix).selectedIndex != -1 && $(fields_prefix+"geo_state_" + postfix).selectedIndex != 0);
        if (is_state) {
            state_value = $(fields_prefix+"geo_state_" + postfix).options[$(fields_prefix+"geo_state_" + postfix).selectedIndex].text;
        }
    }


    is_city = ($(fields_prefix+"geo_city_" + postfix).value != "" );
    if (!(is_country || is_state || is_city || required)) {
        return "";
    }


 //this is inoperative $(fields_prefix+"geo_city_" + postfix ).value;

	//there is no need to validate the country,city values as they are same.
	if( previous_country == country_value && previous_city == city_value &&  previous_state == state_value)
	{
		return "";
	}

    //validate_country(country_value,fields_prefix+'geo_no_country_1',fields_prefix+'geo_country_wait_1');
    validate_city(city_value,country_value,fields_prefix+'geo_no_city_' + postfix,fields_prefix+'geo_city_wait_' + postfix,state_value);
    //validate_state($F("geo_state_1"),$F("geo_country_1"),'geo_no_state_1','geo_state_wait_1');
    errorhtml = "";
    if ( !is_country ) {
        errorhtml += error_list.blank_country + "#";
    }
    /* checking state in case if country is united states of America */
    if (country_value.strip() == "United States of America") {
        /*
                Now we don't need to send the request for verifying the state_list as state list are prefilled
                and its sufficient to check that its selectedIndex != 0 if country 'United States of America' is selected.
            */
        //validate_state(state_value,country_value,fields_prefix+'geo_no_state_1',fields_prefix+'geo_state_wait_1');
        if ( state_value == "" ) {
            errorhtml += error_list.blank_state + "#";
        }
    }

    if ( $(fields_prefix+"geo_city_" + postfix).value == "" ) {
        errorhtml += error_list.blank_city + "#";
    } else if (Element.visible(fields_prefix+'geo_no_city_' + postfix)) {
        errorhtml += error_list.city_not_found  + "#";
    }
    //return error_count + "$" + errorhtml;
    return errorhtml;
}

function isLeapYear(year){
	return ((year%4 == 0) && (year%100 != 0 || year%400 == 0));
}

function readDaysInMonth(month,year){
    if (month == 1 && isLeapYear(year) == true) return 29;
    else return [31,28,31,30,31,30,31,31,30,31,30,31][month];
}

function checkDateForNumberOfDaysInMonth(errorhtml, month, year){
	//checking the date
	days = readDaysInMonth((month-1),year);
	if (days<$("date_day").value) {
    	errorhtml += "The month specified only has " + days + " days."  + "#";
	}
	return errorhtml;
}

/*
    This method is used to validate the edit profile form fields
*/
function validate_profile_form() {
    disable_form('save_profile_form',true);
    remove_previous_error_div();
    var errorhtml    = "";

    if ( $("user_user_name").value == "" ) {
        errorhtml += error_list.blank_username + "#";
    }
    //user_first_name -- validate rule if any
    //user_last_name    -- validate rule if any
    //user_cell_phone  --validation rule will be implemented if its required.
    if ( $("user_user_name").value.length < 5 ) {
        errorhtml += error_list.username_min_length + "#";
    }

	if ($("date_month").value == "")
    {
        errorhtml += "Please select month you were born."  + "#";
    }

	if ($("date_day").value == "")
    {
        errorhtml += "Please select day you were born."  + "#";
    }else{
		errorhtml = checkDateForNumberOfDaysInMonth(errorhtml, $("date_month").value, $("date_year").value);
	}

    var date_year = $("date_year").value;
    var minDate = (new Date()).getFullYear() - 13;
	if (date_year > minDate) {
        errorhtml += "Age should be 13 or more"  + "#";
    }


    /*if ($('user_email').value == "") {
        errorhtml += error_list.blank_email + "#";
    } else if ( !validateemail($("user_email").value) ) {
        errorhtml += error_list.wrong_email + "#";
    }*/


    //profile_image--- its validation is not required as its not mandatory field.
    if ($('profile_image').value!="") {
        if (!checkExtension_img($('profile_image').value)) {
            errorhtml += error_list.unknown_img_format + "#";
        }
    }
    if ($('password_password').value!="" || $('password_confirmpassword').value != "") {
        before_length = errorhtml.length;
        if ( ( $("password_password").value != $("password_confirmpassword").value) ) {
            errorhtml += error_list.confirm_password  +"#";
        }
        //user[gender]--- its validation is not required as its already selected.
        //age--- they are already selected so no need to check it
        //education---they are already selected so no need to check it
        if ( ( $("password_password").value.length < 6 ) ) {
            errorhtml += error_list.minimum_password_length + "#";
        }
        if (before_length < errorhtml.length) {
            $("password_password").value = '';
            $("password_confirmpassword").value = '';
        }
    }


    //validating geo locations
    //valid_country = validate_geo_location().split("$");

    //error_count += parseInt(valid_country[0]);
    errorhtml += validate_geo_location();



    if ( $("levelofeducation").selectedIndex == -1) {
        errorhtml += error_list.blank_education + "#";
    }

    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        if ($('success_status_bar')) {
            Element.remove('success_status_bar');
        }
        new Insertion.Top('save_profile_form',get_error_list_html(errorhtml.split("#"),error_list.update_profile_error_heading,''));
        disable_form('save_profile_form',false);
        return false;
    }
}
/*
    This method is used to validate share-url form on event and people_in_the_news fields
*/
function validate_share_url_form() {
    disable_form('div_urls_rss_form',true);
    var errorhtml = "";
    remove_previous_error_div();
    var form_error_count = 0;

    if ( $F("url") == "" ) {
        errorhtml += error_list.blank_url + "#";
        form_error_count += 1;
    } else if ( !validateurl($F("url")) ) {
        errorhtml += error_list.wrong_url + "#";

        form_error_count += 1;
    }

    if (errorhtml == "") {
        return true; //in case of successful validation
    } else {
        new Insertion.Top('div_urls_rss_form',get_error_div(errorhtml.split("#"),error_list.url_feed_error_heading,''));
        disable_form('div_urls_rss_form',false);
        return false;
    }
}

/*
    This function is using at partial user completion form for validation form fields
*/
function validate_partial_complete(){
	if(typeof(swfu)!='undefined' && swfu.getStats().in_progress == 1)
    {
        alert(error_list.image_upload_progress);
        return false;
    }

    disable_form('signup_form',true,undefined,'div_processing_spinner_partial');
    var errorhtml = "";


    remove_previous_error_div();

    if ($("date_month").value == "")
    {
        errorhtml += "Please select month you were born."  + "#";
    }

	if ($("date_day").value == "") {
        errorhtml += "Please select day you were born."  + "#";
    } else {
		errorhtml = checkDateForNumberOfDaysInMonth(errorhtml, $("date_month").value, $("date_year").value);
	}

    var minDate = (new Date()).getFullYear() - 13;
    var date_year = $("date_year").value;
    if (date_year == "" || date_year > minDate)
    {
        errorhtml += "Age should be 13 or more"  + "#";
    }
    //validating geo locations
    errorhtml  += validate_geo_location();

    if ( $("levelofeducation").selectedIndex == -1 )
    {
        errorhtml += error_list.blank_education +"#";
    }

	if ($("user_terms_of_service")!=null && $("user_terms_of_service").checked!=1)
    {
    	errorhtml += error_list.blank_terms_of_service+ "#";
    }

    if ($("user_privacy_policy")!=null && $("user_privacy_policy").checked != 1)
    {
        errorhtml += error_list.blank_privacy_policy + "#";
    }

    /* check profile_uploaded_image is visibe and swfu is not uploading anything */
    if($('profile_uploaded_image')!=null && $('profile_uploaded_image').visible()==false)
    {
        /*
         *we are not checking the swfu uploading status because we do hide 'profile_uploaded_image' whenever
         *we start uploading of file
         */
        errorhtml += error_list.blank_image + "#";
    }


    if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        new Insertion.Top('registeration_content', get_error_list_html(errorhtml.split("#"),error_list.signup_error_heading,''));
        disable_form('signup_form',false,undefined,'div_processing_spinner_partial');
        return false;
    }
}



/*
    This method is used to validate the login form fields
*/
function validate_login_form() {
    disable_form('login_content',true);
    var errorhtml = "";
    remove_previous_error_div();

    if ($("user_name").value == "") {
        errorhtml += error_list.blank_email + "#";
    } else if ( !validateemail($("user_name").value) ) {
        errorhtml += error_list.wrong_email + "#";
    }

    if ( ( $("password").value.length < 1 ) ) {
        errorhtml += error_list.blank_password + "#";
    }

    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top('login_content',get_error_list_html(errorhtml.split("#"),error_list.login_error_heading,''));
        disable_form('login_content',false);
        return false;
    }
}
/*
    This function is using at sign-up form for validation form fields
*/
function validate_partial_signup_form() {
    disable_form('signup_form',true,undefined,'div_processing_spinner_partial');

	//Element.hide('div_processing_spinner');
	//Element.show('div_processing_spinner_partial');

    var errorhtml = "";
    remove_previous_error_div();

    //validating email address
    if ($('user_email').value == '') {
        errorhtml += error_list.blank_email + "#";
    } else if ( !validateemail($("user_email").value) ){
        errorhtml += error_list.wrong_email + "#";
    }

    //validating username
    if ( $("user_user_name").value == '' ){
        errorhtml += error_list.blank_username + "#";
    } else if ( $("user_user_name").value.length < 5 ){
        errorhtml += error_list.username_min_length + "#";
    }

    //validating password
    before_length = errorhtml.length;

    if ( ( $("user_password").value != $("confirmpassword").value) ){
        errorhtml += error_list.confirm_password + "#";
        new Ajax.Request("/main/change_captcha", {parameters:{}, asynchronous:true,onLoading:function(){}//end onLoading function
		       ,onComplete: function(transport){
		           $('change_captcha').update(transport.responseText);
		       } //end Complete function
		       ,onError: function(){
		           alert("Sorry, Captcha image could not be replaced this time.");
		       }
		      } //end parameters
		);
    }

    if ( ( $("user_password").value.length < 6 ) ){
        errorhtml += error_list.minimum_password_length + "#";
    }
    if (before_length < errorhtml.length) {
        $("confirmpassword").value = '';
        $("user_password").value = '';
    }

	if ($("user_terms_of_service")!=null && $("user_terms_of_service").checked!=1) {
        errorhtml += error_list.blank_terms_of_service+ "#";
    }

    if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        new Insertion.Top('registeration_content', get_error_list_html(errorhtml.split("#"),error_list.signup_error_heading,''));
        disable_form('signup_form',false,undefined,'div_processing_spinner_partial');
		//Element.hide('div_processing_spinner_partial');
        return false;
    }
}

function validateEmailFields(object_field, error_div, spinner) {
	var errorhtml = "";
	//validating email address
	if ($(object_field).value == '') {
	    errorhtml += error_list.blank_email + "#";
	} else if ( !validateemail($(object_field).value) ){
	    errorhtml += error_list.wrong_email + "#";
	}
	
	if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        $(error_div).innerHTML = get_error_list_html(errorhtml.split("#"),"Ooops, something didn't go right there...",'', 'yes');
        $(error_div).show();
		$(spinner).hide();
		return false;
    }
}
/*
    This function is using at sign-up form for validation form fields
*/
function validate_signup_form() {
    disable_form('signup_form',true);
    var errorhtml = "";
    remove_previous_error_div();

    //validating email address
    if ($('user_email').value == '') {
        errorhtml += error_list.blank_email + "#";
    } else if ( !validateemail($("user_email").value) ){
        errorhtml += error_list.wrong_email + "#";
    }

    //validating username
    if ( $("user_user_name").value == '' ){
        errorhtml += error_list.blank_username + "#";
    } else if ( $("user_user_name").value.length < 5 ){
        errorhtml += error_list.username_min_length + "#";
    }

    //validating password
    before_length = errorhtml.length;

    if ( ( $("user_password").value != $("confirmpassword").value) ){
        errorhtml += error_list.confirm_password + "#";
        new Ajax.Request("/main/change_captcha", {parameters:{}, asynchronous:true,onLoading:function(){

        }//end onLoading function
                                                  ,onComplete: function(transport){

                                                      $('change_captcha').update(transport.responseText);
                                                  } //end Complete function
                                                  ,onError: function(){
                                                      alert("Sorry, Captcha image could not be replaced this time.");
                                                  }
                                                 } //end parameters
                        );
    }

    if ( ( $("user_password").value.length < 6 ) ){
        errorhtml += error_list.minimum_password_length + "#";
    }
    if (before_length < errorhtml.length) {
        $("confirmpassword").value = '';
        $("user_password").value = '';
    }


    var date = $("date_year").value;
    var minDate = (new Date()).getFullYear() - 13;
    if (date > minDate)
	{
        errorhtml += "Age should be 13 or more"  + "#";
    }

    //validating geo locations
    errorhtml  += validate_geo_location();

    if ( $("levelofeducation").selectedIndex == -1 ) {
        errorhtml += error_list.blank_education +"#";
    }

	//validating cellphone number
	country_code = $("user_cellphones_country_code").value;
	cellphone = $("user_cellphones_cellphone").value;
    if ( (country_code != '' && isNaN(country_code)) || (cellphone != '' && isNaN(cellphone)) ) {
		errorhtml += error_list.wrong_cellphone + "#";
    }

	//validating pincode
	pincode = $("user_cellphones_pincode").value;
    if ( pincode != '' && (isNaN(pincode) || pincode.length < 5) ) {
		errorhtml += error_list.wrong_pincode + "#";
    }

    if ( $("captcha"    ).value == "" ) {
        errorhtml += "Enter text for Captcha image." + "#";
    }

    if ($("user_terms_of_service")!=null && $("user_terms_of_service").checked != 1) {
        errorhtml += error_list.blank_terms_of_service+ "#";
    }

    if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        new Insertion.Top('registeration_content', get_error_list_html(errorhtml.split("#"),error_list.signup_error_heading,''));
        disable_form('signup_form',false);
        return false;
    }
}

function validate_search_form() {
  if ($('search_box').value.strip()=='' || $('search_box').value.strip()==error_list.searchbox) {
    return false;
  }


   var alnum = new RegExp('[^a-z-0-9A-Z]+');
   $('search_box').value = $('search_box').value.strip().replace(alnum, '-');
   return true;
}

function validate_geosearch_form() {
  if ($('location_search').value.strip()=='' || $('location_search').value.strip()==error_list.locationbox) {
    return false;
  }
  return true;
}


//given a url and an anchor object, hide the anchor and replace with a spinner while
// requesting the URL. Show success or failure when done.
// needs more work to generalize it.
function inline_spinner_ajax(url, anchorObj, spinnerId, success, failure) {
    Element.hide(anchorObj);
    var spinner = $(spinnerId);
    Element.show(spinner);
    new Ajax.Request(url, {
        asynchronous:true,
        onComplete: function(transport) {
            if (transport.responseText.indexOf('success') > -1) {
                if(typeof success == 'function') {
                    success();
                    spinner.style.display = "none";
                } else {
                    spinner.innerHTML = success;
                }
            } else {
                if(typeof failure == 'function') {
                   failure();
                   spinner.style.display = "none";
                } else {
                    spinner.innerHTML = failure;
                }
            }
        }
    });
}

function become_fan(user_name, anchorObj, widgetId, otherSet) {
  var url = domain+'/users/'+user_name+'/become_fan';

  function fanSuccess () {
      $(widgetId + "_fanLink").style.display = "";
      $(widgetId + "_notFanLink").style.display = "none";

      if (otherSet != "" && $(otherSet + '_notFanLink')) {
      	$(otherSet + "_fanLink").style.display = "";
        $(otherSet + "_notFanLink").style.display = "none";
      }
  }

  inline_spinner_ajax(url, anchorObj, widgetId + "_ajaxWait", fanSuccess, 'Weird error. Refresh & try again?');
}
function remove_fan(user_name, anchorObj, widgetId) {
  var url = domain+'/users/'+user_name+'/remove_fan';

  function fanSuccess () {
      $(widgetId + "_fanLink").style.display = "none";
      $(widgetId + "_notFanLink").style.display = "";
  }
  inline_spinner_ajax(url, anchorObj, widgetId + "_ajaxWait", fanSuccess, 'Weird error. Refresh & try again?');
}

function send_friend_request(user_name, containingDiv) {
    var spinner = (containingDiv.getElementsByClassName('ajaxWait'))[0];
    Element.show(spinner);
    var url = domain+'/users/'+user_name+'/request_friendship';
    new Ajax.Request(url, {
        asynchronous:true,
        onComplete: function(transport) {
            if (transport.responseText.indexOf('success') > -1) {
              spinner.innerHTML = error_list['friend_request_success'];
            } else {
              spinner.innerHTML = error_list['friend_request_error'];
            }
        }
    });
}

//todo: user probably expects the lists to rearrange themselves here, no?
function confirm_friend_request(user_name, containingDiv, status) {
    containingDiv.innerHTML = '<p class="ajaxWait"><img src="/images/ajax/ajax-wait-arrows.gif" style="width:16px; height:16px;" /> Saving...</p>';
    var url = domain+'/users/'+user_name+'/confirm_friendship?status='+status;
    new Ajax.Request(url, {
        asynchronous:true,
        onComplete: function(transport) {
            if (transport.responseText.indexOf('success') > -1) {
              containingDiv.innerHTML = error_list['friend_confirm_success'];
            } else {
              containingDiv.innerHTML = error_list['friend_request_error'];
            }
        }
    });
}




/*
    This function used to verify the cellphone setting on the edit_profile form
*/
function send_verification_code() {
    //check cellphone and cellphone(confirm) and they should be numeric
    //disable the cellphone and cellphone(confirm)
    //initiate ajax request to send verification code
    //set the message
    //show picode portion
    progress_element = 'send_verification_message';
    url = domain + "/main/send_verification_code";
    params = "cellphone=" + $('user_cellphone_country_code').value + '-' + $('cell_phone').value;
    div_to_add = 'profile_page';
    var my_error_list = "";

    remove_previous_error_div();
    if ($('cell_phone').value == "") {
        my_error_list += error_list.blank_cellphone;
    } else {
        if (!validate_digits($('cell_phone').value)) {
            my_error_list += "Cellphone - " + error_list.digits_only;
        }
    }


    if ($('user_cellphone_country_code').value == "" || $('user_cellphone_country_code_confirmed').value == "") {
        my_error_list += error_list.blank_country_code;
    } else {
        if ($('user_cellphone_country_code').value !=  $('user_cellphone_country_code_confirmed').value) {
            my_error_list += error_list.confirm_country_code;
        } else {
            if (!validate_digits($('user_cellphone_country_code').value)) {
                my_error_list += "Country Code-" + error_list.digits_only;
            } else if (!validate_digits($('user_cellphone_country_code_confirmed').value)) {
                my_error_list += "Confirm Country Code-" + error_list.digits_only;
            }
        }
    }

    if ($('cell_phone_confirmed').value !=  $('cell_phone').value) {
        my_error_list += error_list.update_profile_confirm_phone;
    } else {
        if (!validate_digits($('cell_phone_confirmed').value)) {
            my_error_list += " Confirmed cellphone - " + error_list.digits_only;
        }
    }
    if (my_error_list  != "") {
        new Insertion.Top($(div_to_add),get_error_div(my_error_list.split("#"),error_list.update_profile_cellphone_error_heading,''));
        return false;
    } else {
        new Ajax.Request(url,{parameters:params,asynchronous:true, onLoading:function() {
            if (typeof progress_element != 'undefined') {
                Element.show(progress_element);
            }
        },onComplete: function(transport) {
            if (dialogbox_response_eval('profile_page',error_list.update_profile_cellphone_error_heading,transport.responseText,'')){
                $('success_msg').update(error_list.update_profile_success_sendverification);
				divAddClassName($('success_msg'), "siteFlashMsg");
                $(progress_element).hide();
                change_status_elements(['btn_send_verify_code','cell_phone_confirmed','cell_phone','user_cellphone_country_code','user_cellphone_country_code_confirmed'],'true');
                Element.show('div_pincode');
            }
        }
                             });
        return false;
    }
}

function divAddClassName(div_name, classtoadd){
	div_name.addClassName(classtoadd);
}

/*
    This function used to verify the cellphone setting on the edit_profile form (SORRY CARLOS, code repeat)
*/
function send_verification_code_email() {
    //check cellphone and cellphone(confirm) and they should be numeric
    //disable the cellphone and cellphone(confirm)
    //initiate ajax request to send verification code
    //set the message
    //show picode portion
    progress_element = 'send_verification_message_email';
    url = domain + "/main/send_verification_code_via_email";
    params = "email=" + $('email').value;
    div_to_add = 'profile_page_email';
    var my_error_list = "";

    remove_previous_error_div();
    if ($('email').value == "") {
        my_error_list += error_list.blank_email;
    } else if ( !validateemail($("email").value) ){
        my_error_list += error_list.wrong_email;
    }

    if ($('email_confirmed').value !=  $('email').value) {
        my_error_list += error_list.update_profile_confirm_email;
    }

    if (my_error_list  != "") {
        new Insertion.Top($(div_to_add),get_error_div(my_error_list.split("#"),error_list.update_profile_email_error_heading,''));
        return false;
    } else {
        new Ajax.Request(url,{parameters:params,asynchronous:true, onLoading:function() {
            if (typeof progress_element != 'undefined') {
                Element.show(progress_element);
            }
        },onComplete: function(transport) {
            if (dialogbox_response_eval('profile_page_email',error_list.update_profile_email_error_heading,transport.responseText,'')){
                $('success_msg_email').update("Email is successfully sent.");
				divAddClassName($('success_msg_email'), "siteFlashMsg");
                $(progress_element).hide();
                change_status_elements(['btn_send_verify_code_email','email_confirmed','email'],'true');
                Element.show('div_pincode_email');
            }
        }
                             });
        return false;
    }
}

/*
    This function used to verify the pincode against provided cellphone
*/
function veritfy_pincode() {
    div_to_add = 'profile_page';
    progress_element = 'verification_pincode_message';
    url = domain + "/main/verify_cellphone";
    params = "cellphone=" + $('user_cellphone_country_code').value + "-" + $('cell_phone').value + "&pincode=" + $('pin_code').value;
    var my_error_list = "";

    if ($('pin_code').value == "") {
        my_error_list += error_list.update_profile_blank_pincode;
    }
    if (!validate_digits($('pin_code').value)) {
        my_error_list += error_list.digits_only;
    }
    if (my_error_list != "") {
        new Insertion.Top($(div_to_add),get_error_div(my_error_list.split("#"),error_list.update_profile_pincode_error_heading,''));
        return false;
    } else {
        new Ajax.Request(url,{parameters:params,asynchronous:true, onLoading:function() {
            if (typeof progress_element != 'undefined') {
                Element.show(progress_element);
            }
        },onComplete: function(transport) {
            if (dialogbox_response_eval('profile_page',error_list.update_profile_pincode_error_heading,transport.responseText,'')){
                $('success_msg').update(error_list.update_profile_success_pincode_msg);
				divAddClassName($('success_msg'), "siteFlashMsg");
                $(progress_element).hide();
                //Element.hide('div_pincode');
                change_status_elements(['btn_send_verify_code','cell_phone_confirmed','cell_phone','pin_code','btn_verify_pincode','user_cellphone_country_code','user_cellphone_country_code_confirmed'],'true');
                //clear_txt_fields(['cell_phone_confirmed','cell_phone','pin_code']);
            } else {
                hide_element_shown(progress_element);
            }
        }
                             });
        return false;
    }
}

/*
    This function used to verify the pincode against provided email
*/
function verify_email_pincode() {
    div_to_add = 'profile_page_email';
    progress_element = 'verification_pincode_message_email';
    url = domain + "/main/verify_email";
    params = "email=" + $('email').value + "&pincode=" + $('email_pin_code').value;
    var my_error_list = "";

    if ($('email_pin_code').value == "") {
        my_error_list += error_list.update_profile_blank_pincode;
    }
    if (!validate_digits($('email_pin_code').value)) {
        my_error_list += error_list.digits_only;
    }
    if (my_error_list != "") {
        new Insertion.Top($(div_to_add),get_error_div(my_error_list.split("#"),error_list.update_profile_pincode_error_heading,''));
        return false;
    } else {
        new Ajax.Request(url,{parameters:params,asynchronous:true, onLoading:function() {
            if (typeof progress_element != 'undefined') {
                Element.show(progress_element);
            }
        },onComplete: function(transport) {
            if (dialogbox_response_eval('profile_page',error_list.update_profile_pincode_error_heading,transport.responseText,'')){
                $('success_msg_email').update("Now, your email is verified successfully.");
				divAddClassName($('success_msg_email'), "siteFlashMsg");
                $(progress_element).hide();
                //Element.hide('div_pincode');
                change_status_elements(['btn_send_verify_code_email','email_confirmed','email','email_pin_code','btn_verify_pincode_email'],'true');
                //clear_txt_fields(['cell_phone_confirmed','cell_phone','pin_code']);
            } else {
                hide_element_shown(progress_element);
            }
        }
                             });
        return false;
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////   Basic Validation functions   ///////////////////////////////////////////
//////////////////////////////////                                ///////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
    validation for content message boxes
*/
/*function validate_share_content(value, yourname, youremail, captcha, div_to_add,style) { */
function validate_share_content(value, yourname, youremail, div_to_add,style) {
    validate_email = validate_multiemails(value);
    if (yourname.value.length == 0) {
        validate_email += "Your name cannot be empty#";
    }
    if (yourname.value.length > 0 && yourname.value[0]==' ') {
        validate_email += "Your name should not start with space#";
    }
    if (youremail.value.length == 0) {
        validate_email += "Your email cannot be empty#";
    }

    /*if (captcha.value.length != 6) {
        validate_email += "Please enter the 6 letters in the picture#";
    }*/

    if (validate_email == "") {
        return true;
    } else {
        error_div = $(div_to_add);
        if (!error_div.visible()) {
            error_div.show();
        }
        //error_div.update('');

        new Insertion.Top($(div_to_add),get_error_div(validate_email.split("#"),error_list.wrong_email_heading,style));

        return false;
    }
}


function validate_share_content_with_captcha(value, yourname, youremail, captcha, div_to_add,style) {
    validate_email = validate_multiemails(value);
    if (yourname.value.length == 0) {
        validate_email += "Your name cannot be empty#";
    }
    if (yourname.value.length > 0 && yourname.value[0]==' ') {
        validate_email += "Your name should not start with space#";
    }
    if (youremail.value.length == 0) {
        validate_email += "Your email cannot be empty#";
    }

    if(typeof(Recaptcha)!='undefined')
    {
        if(Recaptcha.get_response().strip().length<0)
        {
            validate_email += "Please enter the 6 letters in the picture#";
        }
    }
    else if (captcha.value.length != 6)
    {
        validate_email += "Please enter the 6 letters in the picture#";
    }

    if (validate_email == "") {
        return true;
    } else {
        error_div = $(div_to_add);
        if (!error_div.visible()) {
            error_div.show();
        }
        error_div.update('');

        new Insertion.Top($(div_to_add),get_error_list_html(validate_email.split("#"),error_list.wrong_email_heading,style));

        return false;
    }
}

function get_all_email_address()
{
    var email_addresses = '';
    var page_url = encodeURIComponent($('page_url').value);
    var content_type = 'Event';
    var invite_messag= encodeURIComponent($('invite_message').value);
    var invite_emails = "";
    var share ='Share';
    var all_params= '';


    if(validate_multiemails($('invite_email_address').value,true)=="")
    {
        invite_emails = $('invite_email_address').value;
    }
    var my_contacts = ($('contactsTable') ? $('contactsTable') : $('contactsTable_inline'))
    if(my_contacts)
    {
        var checkboxes = my_contacts.getElementsByTagName("INPUT");   // get checks in form
        var no_of_checked = 0;
        for(var i = 0; i < checkboxes.length; i++)
        {
            if(checkboxes[i].type == "checkbox" && checkboxes[i].checked)
            {
                email_addresses += $('email_'+i).innerHTML.strip() + ",";
                no_of_checked +=1;
            }
        }
    }
    email_addresses += invite_emails;
    all_params = "page_url="+page_url+"&content_type="+content_type+"&inivite_message="+ invite_messag +  "&invite_email_address="+encodeURIComponent(email_addresses)+"&share=Share";
    return all_params;
}

/* This function is used at event page for validating event invitation */
function validate_invite_friend(email_addresses, div_to_add,style) {
    validate_email = validate_multiemails(email_addresses,true);
	if (validate_email == "" || validate_import_contacts()) {
        return true;
    }
    else
    {
        error_div = $(div_to_add);
        if (!error_div.visible())
        {
            error_div.show();
        }
        //error_div.update('');
        new Insertion.Top($(div_to_add),get_error_div(validate_email.split("#"),error_list.wrong_email_heading,style));
        return false;
    }
}

function validate_import_contacts()
{
    var contacts =($('contactsTable') ? $('contactsTable') : $('contactsTable_inline'));
    if(contacts)
    {

        var checkboxes = contacts.getElementsByTagName("INPUT");;   // get checks in form
        var no_of_checked = 0;
        for(var i = 0; i < checkboxes.length; i++)
        {
            if(checkboxes[i].type == "checkbox" && checkboxes[i].checked)
            {
                no_of_checked +=1;
            }
        }
        return (no_of_checked>0 ? true : false);
    }else
    {
        return true;
    }
}


/*
    validate multiple emails
*/
function validate_multiemails(emailaddresses,is_multi_email) {
    var email_list = emailaddresses.replace(/\s+/g,'').split(',');
    var error_message_list = "";
    if ( emailaddresses == "" || emailaddresses.strip() == error_list.enter_email_address)
    {
        //please enter valid email addresses
        if(typeof(is_multi_email) != "undefined")
		{
			error_message_list += error_list.blank_multi_email + "#";
		}
		else
		{
			error_message_list += error_list.blank_email + "#";
		}
        return error_message_list;
    }

    for(i=0; i<email_list.length; i++) {
        if (email_list[i] == '' || validateemail(email_list[i]) == false) {
            error_message_list += error_list.wrong_email_address+"#";
            break;
        }
    }
    return error_message_list;
}
/*
    this function is used to validate email adddress
*/
function validateemail(emailaddress) {
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return filter.test(emailaddress);
}
/*
    this function is used to validate url
*/
function validateurl(url) {
    var filter=/^(((http|https|ftp):\/\/)?)(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i;
    return filter.test(url);
}
/*
    This function will used for validating numeric only fields
*/
function validate_digits(value) {
    var filter=/[^\d]/;
    if (filter.test(value)) {
        return false;
    }
    return true;
}
/*
    This method is used for checking image file
    We will change known_ext as we start supporting more image formats
    paramater ::
                file_field_value :: value of image field
*/
function validate_image_file(file_field_value) {
    var known_ext = new Array ('.jpg', '.gif', '.jpeg', '.png', '.bmp', '.JPG', '.GIF', '.JPEG', '.PNG', '.BMP');
    var status= 0;
    for (i = 0; i < known_ext.length; i++) {
        if (file_field_value.indexOf(known_ext[i]) != -1) {
            status = 1; // one of the file extensions found
        }
    }
    if (status == 1) {
        return true;
    } else {
        return false;
    }
}
/*
    Image validation functions
*/
function checkExtension_img(str) {
    str = str.toString();
    var segments = str.split (".");
    if ( segments.length == 1) {
        return false;
    }

    var ext = segments[segments.length-1];
    ext = ext.toLowerCase();
    if (ext=="jpg" || ext=="gif" ||ext=="png" ||ext=="jpeg" || ext=="bmp") {
        return true;
    }
    return false;
}
/*
    Video validation function
*/
function checkExtension_vid(str) {
    str = str.toString();
    var segments = str.split (".");
    if ( segments.length == 1) {
        return false;
    }
    ext = segments[segments.length-1];
    ext = ext.toLowerCase();
    if (ext=="mpeg" || ext=="mp4" ||ext=="mov" ||ext=="mpg" || ext=="avi"  ||ext=="wmv" || ext=="3gp") {
        return true;
    }
    return false;
}

/* this function used to cancel the file uploads when we press cancel button.*/
function cancel_images_videos_upload() {
    new Ajax.Request('/main/cancel_images_videos_upload', {asynchronous:true, evalScripts:true,
                                                           onComplete:function(request){

                                                           }
                                                          });
}

/*function used for deleting record on manage_blog page*/
function delete_record(id) {
    if (confirm_submit("Are you sure you want to delete this blog?")) {
        $('status_msg_' + id).value = "please wait";
        Element.visible('status_msg_' + id);
        remove_previous_error_div();
        Element.hide('status_message');

        new Ajax.Request('/blog/delete_blog/'+id, {asynchronous:true, evalScripts:true, onComplete:function(request){
            if (dialogbox_response_eval('display_error','error prohibited this Blog from being deleted',request.responseText,'width:555px')){
                oRequestHandlers[0].update("manage_blog");
                $('message_content').update("Blog is deleted successfully");
                Element.show('status_message');
            }
        }
                                                  });
    }
}
/*function used for deleting record on manage_video page*/

function delete_video(id) {
    if (confirm_submit("Are you sure you want to delete this video?")) {
        $('status_msg_' + id).value = "please wait";
        Element.visible('status_msg_' + id);
        remove_previous_error_div();
        Element.hide('status_message');

        new Ajax.Request('/video/delete_video/'+id,{asynchronous:true, evalScripts:true, onComplete:function(request){
            oRequestHandlers[0].update("manage_video");
            $('message_content').update("Video is deleted successfully");
            Element.show('status_message');
        }

                                                   });
    }
}

/*function used for deleting record on manage_video page*/

function delete_image(id) {
    if (confirm_submit("Are you sure you want to delete this image?")) {
        $('status_msg_' + id).value = "please wait";
        Element.visible('status_msg_' + id);
        remove_previous_error_div();
        Element.hide('status_message');

        new Ajax.Request('/image/delete_image/'+id,{asynchronous:true, evalScripts:true, onComplete:function(request){
            oRequestHandlers[0].update("manage_image");
            $('message_content').update("Image is deleted successfully");
            Element.show('status_message');
        }

                                                   });
    }
}


/*function used to confirm  message*/
function confirm_submit(message) {
    var agree=confirm(message);
    if (agree) {
        return true ;
    } else {
        return false ;
    }
}
/*function used for publish record on manage_blog page*/
function publish_record(id) {
    if (confirm_submit("Are you sure to publish this blog?")) {
        try{
            Element.hide('status_message');
            $('status_msg_' + id).value = "please wait";
            Element.visible('status_msg_' + id);
            remove_previous_error_div();
            status_message_div();
            new Ajax.Request('/blog/publish_blog/'+id, {
                asynchronous:true,
                evalScripts:true,
                onComplete:function(request){
                    if (dialogbox_response_eval(
                        'display_error',
                        'error prohibited this Blog from being published',
                        request.responseText,
                        'width:555px')) {
                        oRequestHandlers[0].update("manage_blog");
                        $('message_content').update("Blog is published successfully");
                        Element.show('status_message');
                    }
                }
            });
        } catch(e) {
            log_exceptions("Method :- publish_record " + e.message);
        }
    }
}


/*function used for publish record on manage_video page*/
function publish_video(id) {
    if (confirm_submit("Are you sure to publish this video?")) {
        try{
            Element.hide('status_message');
            $('status_msg_' + id).value = "please wait";
            Element.visible('status_msg_' + id);
            remove_previous_error_div();
            status_message_div();
            new Ajax.Request('/video/publish_video/'+id, {
                asynchronous:true,
                evalScripts:true,
                onComplete:function(request){
                    oRequestHandlers[0].update("manage_video");
                    $('message_content').update("Video is published successfully");
                    Element.show('status_message');
                }

            });
        } catch(e) {
            log_exceptions("Method :- publish_video " + e.message);
        }
    }
}

/*function used for publish record on manage_image page*/
function publish_image(id) {
    if (confirm_submit("Are you sure to publish this image?")) {
        try {
            Element.hide('status_message');
            $('status_msg_' + id).value = "please wait";
            Element.visible('status_msg_' + id);
            remove_previous_error_div();
            status_message_div();
            new Ajax.Request('/image/publish_image/'+id, {asynchronous:true, evalScripts:true, onComplete:function(request){
                oRequestHandlers[0].update("manage_image");
                $('message_content').update("Image is published successfully");
                Element.show('status_message');
            }

                                                         });
        }
        catch(e) {
            log_exceptions("Method :- publish_image " + e.message);
        }
    }
}


function validate_invitation_form() {
    disable_form('div_invitation',true);
    var errorhtml = "";

    if ( $F("invitation_to") == "" ){
        errorhtml += "No recepient is mentioned" + "#";
    } else if (validate_multiemails($F("invitation_to"))) {
        errorhtml += "Enter valid email-address" + "#";
    }

    if ( $F("invitation_sub") == "" ){
        errorhtml += "Subject is empty" + "#";
    }

    if ( $F("invitation_body") == "" ){
        errorhtml += "Body is empty" + "#";
    }

    if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        new Insertion.Top('div_invitation',get_error_div(errorhtml.split("#"),error_list.update_profile_invitation_error_heading,''));
        disable_form('div_invitation',false);
        return false;
    }
}

/*
Parameters :
           error_list : -List of errors that is already splitted by comma
                        -Its type can be string or array depending on the numbers
                              of errors.

*/
function get_error_div(error_list,error_heading,style,my_class,postfix) {
    error_count = 0;
    errorhtml = "";
    if ( typeof (my_class) == "undefined") {
        my_class = 'errorExplanation';
    }

    if ( typeof(postfix) == 'undefined' ) {
        postfix ='';
    }

    if ( typeof (error_list.length) != "undefined") {
        //alert("Error_list :: " + error_list.length);
        for(i=0; i<error_list.length; i++) {
            if (error_list[i] != "") {
                errorhtml  += "<li>" + error_list[i] + "</li>";
                error_count++;
            }
        }
    } else {
        errorhtml = "<li>" +  error_list + "</li>";
    }

    if ($('errorExplanation'+postfix)) //removing previous displayed div

    {
        Element.remove('errorExplanation'+postfix );
    }

    if (style.length > 0) {
        preerrorhtml = "<div id='errorExplanation" + postfix  +  "' class='" + my_class + "' style='" + style + "'>";
    } else {
        preerrorhtml = "<div id='errorExplanation"+ postfix +"' class='errorExplanation'>";
    }
    preerrorhtml += "<h2>" + error_count + " " + error_heading + "</h2>";
    preerrorhtml += "<p>There were problems with the following fields:</p><br/><div class='heightclear'></div>";
    preerrorhtml += "<ul>" + errorhtml + "</ul>";
    preerrorhtml += "<div class='clear'></div></div>";
    return preerrorhtml;
}
/*

a new, cleaner version of the get_error_div function, with cleaner code and a simple style set
Parameters :
           error_list : -List of errors that is already splitted by comma
                        -Its type can be string or array depending on the numbers
                              of errors.

*/
function get_error_list_html(error_list, error_heading, postfix, short_error) {
    var error_count = 0;
    var errorhtml = "";

    if ( typeof(postfix) == 'undefined' ) {
        postfix ='';
    }

	if ( typeof(short_error) == 'undefined' ) {
        short_error ='';
    }
    if ( typeof (error_list.length) != "undefined") {
        for(var i=0; i < error_list.length; i++) {
            if (error_list[i] != "") {
				if(short_error == ""){
	                errorhtml  += "<li>" + error_list[i] + "</li>";
	            } else {
					errorhtml  += error_list[i] + "<br/>";
				}
				error_count++;
            }
        }
    } else {
        errorhtml = "<li>" +  error_list + "</li>";
    }

    if ($('errorList'+postfix)) { //removing previous displayed div
        Element.remove('errorList'+postfix );
    }

	if(short_error == ""){
 	   var errorListHtml = "<div id=\"errorList" + postfix + "\" class=\"errorList\">";
	    errorListHtml += "<div class=\"errorListInner\">";
	    errorListHtml += "<h5>" + error_count + " " + error_heading + "</h5>";
	    //errorListHtml += "<p>There were problems with the following fields:</p>";
	    errorListHtml += "<ul>" + errorhtml + "</ul>";
	    errorListHtml += "</div></div>";
	} else{
		errorListHtml = errorhtml;
	}
    return errorListHtml;
}
/*
    This function evaluate the response of dialogboxes like
    comments, questions.
    parameters :1 = div in which error has to inserted
                2 = element to show again
                3 = comma separated element/elements to hide if response is ok
                4 = Error heading like this user from being saved,or Question could not be saved
                5 = json_data ---its properties should be status[ok,cancel], error [comma separated errors]
    //for now i'm leaving two parameters element_to_show,elements_to_hide later we can include these ones
    function dialogbox_response_eval(div_to_add,element_to_show,elements_to_hide,error_heading, json_data)
*/
function dialogbox_response_eval(div_to_add,error_heading, json_text,style) {
    try
    {
        dialog_response = eval(json_text);
        remove_previous_error_div();
        //alert(style);
        if (typeof(dialog_response.status) == "undefined") {
            //alert("this case will be handled later");
            return true;
        }

        if (dialog_response.status =="ok") {
            //hide the elements
            //close the dialog
            return true;
        } else if (dialog_response.status =="cancel") {
            if ($(div_to_add) == null) {
                return false;
            }
            //build error div
            //insert the div
            //show elements
            if ($('errorList')) { //removing previous displayed div
                Element.remove('errorList');
            }
            if (! $(div_to_add).visible()) {
                Element.show(div_to_add);
            }
            /*
                chekcing user authentication
            */
            if ((error_list.session_time_out+"#") == dialog_response.error) {
                alert(error_list.session_time_out);
                window.location.reload();
                //document.location = location.protocol + '//' + location.host + "/login"
                return;
            } else {
                new Insertion.Top($(div_to_add),get_error_list_html(dialog_response.error.split("#"),error_heading));
            }
        }
    } catch(ex) {
        log_exceptions("Method :- dialogbox_response_eval " + ex.message);
    }
}

/*function to get randome */
function rand ( n ) {
    return (  Math.random ( ) );
}

/*this method is used to reset map on default values on following cases
-hide map either by low bandwith link/hide map
-clicking logo of allvoices
*/
function reset_ne_se_cookies() {
    setCookie("northeast","77.07878389624943,-178.2421875");
    setCookie("southwest","-56.75272287205734,-166.9921875");
    setCookie("map_center_and_zoom","10.163030512096046,7.382812500000013,2");
    //document.cookie = 'northeast=' + '77.07878389624943, -178.2421875;path=/';
    //document.cookie = 'southwest='+ '-56.75272287205734, -166.9921875;path=/';
    //document.cookie = 'map_center_and_zoom=' + '10.163030512096046, 7.382812500000013,2;path=/';
}
function parseCookie(index,cookie_name) {
    var val = readCookie(cookie_name);
    val_arr = val.split(",");
    if (index < val_arr.length) {
        return val_arr[index] ;
    }
    return "";
}


function validate_create_event_form(div_to_add,optional_width,post_fix) {


/*	if(!is_spell_check_done)
	{
		if(confirm_submit(error_list.spellchecker_contents))
		{
			tinyMCE.activeEditor.execCommand('mceSpellCheck');
			return false;
		}

	}
*/
	if (typeof(post_fix) == 'undefined')
	{
        post_fix='';
    }

    var errorhtml = "";

    //tinyMCE.triggerSave();

    if ($('title'+post_fix).value.strip()=="") {
        errorhtml += "Title cannot be empty.#";
    }

    my_values = get_tiny_mce_value('summary'+post_fix);
    if(typeof(my_values) != "object")
	{
		return false;
	}

	disable_form(div_to_add,true);
    remove_previous_error_div();

	if ( my_values.text_value == '' || my_values.is_empty == true ) {
        errorhtml += error_list.blank_body + "#";
    }

    /*<p>&nbsp;</p> for safari text area*/
    /*$('summary').value = tinyMCE.activeEditor.getContent();
    if ($('summary').value=="" || $('summary').value=="<p>&nbsp;</p>") {
        errorhtml += "You must enter some description for this event.#";
    }*/

    /*if ($('category').value==-1) {
            errorhtml += "<li>You must select a category for this event.</li>";
            error_count++;
    }*/

	//no need to validate geolocation if event is being created from content
    //validating geo locations

    errorhtml += validate_geo_location('event_');

    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        style = '';
        if (typeof optional_width != "undefined") {
            style = optional_width;
        }
        new Insertion.Top(div_to_add,get_error_list_html(errorhtml.split("#")," error(s) prohibited this form from being saved",style,''));
        disable_form(div_to_add,false);
        return false;
    }
}

function validate_create_person_form(div_to_add,optional_width) {
    disable_form(div_to_add,true);
    var errorhtml = "";
    if ($('title').value=="") {
        errorhtml += "Title cannot be empty.#";
    }
    if (tinyMCE.get('summary').getContent()=='') {
        errorhtml += "You must enter biography of this Person.#";
    }
    /*if ($('category').value==-1) {
            errorhtml += "<li>You must select a category for this event.</li>";
            error_count++;
    }*/
    //validating geo locations
    errorhtml += validate_geo_location('person_');

    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        style = '';
        if (typeof optional_width != "undefined") {
            style = optional_width;
        }
        new Insertion.Top(div_to_add,get_error_div(errorhtml.split("#")," error(s) prohibited this form from being saved",style,'errorExplanation_ans'));
        disable_form(div_to_add,false);
        return false;
    }
}


function validate_share_content_for_person() {
    validate_email = validate_multiemails($('email_address').value);
    if (validate_email == "") {
        return true;
    } else {
        new Insertion.Top('share_error',get_error_div(validate_email.split("#"),"error prohibited this person from being shared",300,'errorExplanation_ans'));
        return false;
    }
}

function validate_share_content_for_event() {
    validate_email = validate_multiemails($('email_address').value);
    if (validate_email == "") {
        return true;
    } else {
        new Insertion.Top('share_error',get_error_div(validate_email.split("#"),"error prohibited this person from being shared",300,'errorExplanation_ans'));
        return false;
    }
}



function validate_feedback_email_form() {
    disable_form('div_feedback_email',true);
    var errorhtml = "";

    if ($('feedback_name').value=='') {
        errorhtml += "You must enter your name.#";
    }
    if ($('feedback_email').value=='') {
        errorhtml += "You must specify your email.#";
    }
    if ($('feedback_subject').value=='') {
        errorhtml += "You must enter a subject.#";
    }
    if ($('feedback_body').value=='') {
        errorhtml += "Your message cannot be empty.#";
    }
    if (!validateemail($('feedback_email').value)) {
        errorhtml += "Please enter the email in a correct format.#";
    }
    if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        new Insertion.Top('div_feedback_email',get_error_div(errorhtml.split("#"),"caused your registration to fail",''));
        disable_form('div_feedback_email',false);
        return false;
    }
}

function validate_image_upload_form(type,div_to_add) {

	var my_tinymce_values = get_tiny_mce_value('shared_image_desc_1');

	if(typeof(my_tinymce_values) != "object")
	{
		return false;
	}

	disable_form(div_to_add,true);
    if (typeof(type) == 'undefined')
	{
        type = '';
    }

    if (typeof(div_to_add) == 'undefined') {
        div_to_add = 'div_image_upload_form';
    }

    var errorhtml = "";

    remove_previous_error_div();
    //tinyMCE.triggerSave();
    if ($('shared_image_title_1').value.gsub(" ","")=='') {
        errorhtml += "Title cannot be empty.#";
    }
    if (type != 'manage') {
        if ($('shared_image_1').value.gsub(" ","")=='') {
            errorhtml += "No image selected. Please select an image.#";
        } else if (!checkExtension_img($('shared_image_1').value.gsub(" ",""))) {
            errorhtml +=  error_list.unknown_img_format + "#";
        }

        /*is_description_empty = false;
        $('shared_image_desc_1').value = tinyMCE.activeEditor.getContent();
        shared_image_description = $('shared_image_desc_1').value.strip();

		if (shared_image_description != '')
		{
        	is_description_empty = get_tinymce_textbox_value();
        }*/

		shared_image_description = my_tinymce_values.text_value;
		is_description_empty = my_tinymce_values.is_empty;

        if (shared_image_description == ''  || is_description_empty == true) {
            errorhtml += "Description cannot be empty.#";
        }
    }

	//errorhtml += validate_geo_location('','optional');

    if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        new Insertion.Top($(div_to_add),get_error_list_html(errorhtml.split("#"),error_list.image_error_heading,''));
		disable_form(div_to_add,false);
        return false;
    }
}


function validate_video_upload_form(type) {
	var my_values = get_tiny_mce_value('shared_video_desc_1');

	if( typeof(my_values) != "object")
	{
		return false;
	}

	disable_form('div_video_upload_form',true);
    var errorhtml = "";
    remove_previous_error_div();
    //tinyMCE.triggerSave();

    if ($('shared_video_title_1').value.gsub(" ","")=='') {
        errorhtml += "Title cannot be empty.#";
    }

    validate_geo_location('','optional');

    if (type != 'manage') {
        if ($('shared_video_1').value.gsub(" ","")=='' && $('youtube_link').value.gsub(" ","")=='') {
            errorhtml += "No Video selected. Please select a Video.#";
        } else if ($('shared_video_1').value.gsub(" ","")!='' && !checkExtension_vid($('shared_video_1').value.gsub(" ",""))) {
            errorhtml += error_list.unsupported_format + "#";
        }


		shared_video_description = my_values.text_value;
		is_description_empty = my_values.is_empty;
		/*is_description_empty = false;
        $('shared_video_desc_1').value = tinyMCE.activeEditor.getContent();
        shared_video_description = $('shared_video_desc_1').value.strip();
        if (shared_video_description != '') {
            is_description_empty = get_tinymce_textbox_value();
        }*/

        if (shared_video_description == ''  || is_description_empty == true) {
            errorhtml += "Description cannot be empty.#";
        }
        //if ($('shared_video_desc_1').value.strip() == '')
        //{
        //    errorhtml += "Description cannot be empty.#";
        //}
    }

    //errorhtml += validate_geo_location('','optional');

    if ( errorhtml == "" ){
        //disable_form('div_video_upload_form');
        return true; //in case of successful validation
    } else {
        new Insertion.Top('div_video_upload_form', get_error_list_html(errorhtml.split("#"),error_list.video_error_heading,''));
		disable_form('div_video_upload_form',false);
        return false;
    }

}
// ####### The function to update event on event page

function updateEvent(id,post_fix)
{
    if (typeof(post_fix) == 'undefined') {
        post_fix='';
    }

	//tinyMCE.triggerSave();

    if (!validate_create_event_form('update_event_form'+post_fix,'510px',post_fix)){
    	return false;
    }

	new Ajax.Request('/event/update_event/'+id, {
        asynchronous:true,
        evalScripts:true,
        onComplete:function(request){
            if (dialogbox_response_eval('div_update_event_form'+post_fix,'error prohibited this event from being saved' ,request.responseText,'')){
                
                // needs some testing
                if (post_fix!='') {
                    oRequestHandlers[0].clearCache();
                    oRequestHandlers[0].update('userevents');
                    oRequestHandlers[0].clearCache();
                    oRequestHandlers[0].update('user_updates');
                    RedBox.close();
                } else {
                    Element.show('div_update_event_spinner'+post_fix);
                    Element.hide('update_event_form'+post_fix);
                    Element.show('div_update_event_form'+post_fix);
                    /*$('event_title_'+id).update($('title'+post_fix).value);
                    $('event_summary_'+id).update('');
                    $('event_summary_'+id).innerHTML=tinyMCE.activeEditor.getContent();
                    if ($('tag_list').value.strip() != "")
                        $('tags_'+id).update("<span>Tags:</span>"+$('tag_list').value);
                    else
                        $('tags_'+id).update('');
                    $('location_span_country').update($('event_geo_city_1').value);
                    $('location_span_name').update($('event_geo_country_1').value);
                    category_id = $('category').options[$('category').selectedIndex].value;*/

                    window.location.reload();

                    RedBox.close();
                }
                //change_category_selection(category_id);
            }else {

                {
                    Element.hide('div_update_event_spinner'+post_fix);
                    Element.show('div_update_event_form'+post_fix);
					disable_form('div_update_event_form'+post_fix,false);
					//alert(request.responseText.error);
					errorhtml = "Summary has not been updated#";
					new Insertion.Top('update_event_form'+post_fix,get_error_div(errorhtml.split("#")," error(s) prohibited this form from being saved",style,'errorExplanation_ans'));
				}

            }
        },
        onLoading:function(request){
            Element.hide('div_update_event_form'+post_fix);
            Element.show('div_update_event_spinner'+post_fix);
        },
        parameters:$('update_event'+post_fix).serialize()
        /*"title="+$('title').value+"&summary="+$('summary').value+"&event[category]="+$('category').options[$('category').selectedIndex].value+"&tag_list="+$('tag_list').value+"&required="+$('required').value+"&event_geo[country_1]="+$('event_geo_country_1').options[$('event_geo_country_1').selectedIndex].value+"&event_geo[state_1]="+$('event_geo_state_1').options[$('event_geo_state_1').selectedIndex].value+"&event_geo[city_1]="+$('event_geo_city_1').value+"&event[visible]="+$('event_visible').checked+"&create_event="+$('create_event').value+"&submit"*/
    });

}


// ####### The function to update event on event page

function updatePerson(id){
    tinyMCE.triggerSave();
	Element.hide('div_update_person_form');
    Element.show('div_update_person_spinner');
    if (!validate_create_person_form('div_create_person','510px')){
		Element.hide('div_update_person_spinner');
		Element.show('div_update_person_form');
        return false;
    }

    new Ajax.Request('/person/update_person/'+id, {
        asynchronous:true,
        evalScripts:true,
        onComplete:function(request){
            if (dialogbox_response_eval('div_create_person','error prohibited this person from being updated' ,request.responseText,'')){

                // reload page differently depending on the values of checkboxes.
                //try{
                //if (!$('person_visible').checked) {
                //    window.location ="/people";
                //}
                //if ($('person_deleted').checked) {
                //    window.location ="/people";
                //} //else {
                //    window.location.reload();
                //}
                //}catch(e){}

                // needs some testing
				try
				{
					Element.hide('div_update_person_spinner');
					Element.hide('update_person_form');
					Element.show('div_update_person_form');
					$('person_title_'+id).update($('title').value);
					$('person_summary_'+id).update('');
					$('person_category').update($('category').options[$('category').selectedIndex].text);
					$('person_summary_'+id).innerHTML=tinyMCE.get('summary').getContent();
					$('location_span_country').update($('person_geo_city_1').value);
					$('location_span_name').update($('person_geo_country_1').value);
					category_id = $('category').options[$('category').selectedIndex].value;
				}catch(ex)
				{
                    ex=ex;
                    log_exceptions(" Method :- callback of update_person " + ex.message);
				}

				RedBox.close();

				/* reload the page */
				window.location.reload();


                //change_category_selection(category_id);
            }else {
                Element.hide('div_update_person_spinner');
                Element.show('div_update_person_form');
            }
        },
        onLoading:function(request){
        },
        parameters:$('update_person').serialize()
    });
}

function updateContent(id, is_profile){
    //evalScripts:true,
    /*on_complete_method = function(request){
                                 // needs some testing
                                 try{
                                     Element.hide('blog_edited_success_'+id);
                                    Element.hide('blog_edited_failed_'+id);
                                    Element.show('blog_edited_progressbar_'+id);
                                    oRequestHandlers[0].clearCache();
                                    oRequestHandlers[0].update('blogs');
                                 }catch(e) {
                                      alert(e.message);
                                 }
                            }
            on_load_method = function(request){
                                try
                                {
                                    RedBox.close();
                                    Element.show('blog_edited_progress_'+id);
                                }catch(e) {
                                     alert(e.message);
                                 }
                            }


        try
        {

        my_url = '/save_blog/'+is_profile;
        posted_variables = Form.serialize('edit_blog_form_profile_'+id);
        new Ajax.Request(my_url, {parameters:posted_variables, asynchronous:true,onLoading:on_load_method,onComplete:on_complete_method});
            //new Ajax.Request(my_url,{parameters:$('edit_blog_form_profile_'+id).serialize(),asynchronous:true,onComplete:on_complete_method,onLoading:on_load_method });
        }catch(ex) {
            alert(ex.message);
        }*/
    my_url = '/save_blog/'+is_profile;
    posted_variables = Form.serialize('edit_blog_form_profile_'+id);
    new Ajax.Request(my_url, {parameters:posted_variables, asynchronous:true,
                              onLoading:function(request) {
                                  RedBox.close();
                                  Element.show('blog_edited_progress_'+id);
                              },
                              onComplete:function(request){
                                  // needs some testing
                                  Element.hide('blog_edited_success_'+id);
                                  Element.hide('blog_edited_failed_'+id);
                                  Element.show('blog_edited_progressbar_'+id);
                                  oRequestHandlers[0].clearCache();
                                  oRequestHandlers[0].update('blogs');
                                  oRequestHandlers[0].update('user_updates');
                              }});

}

function validate_comment_length(max_length) {
    /*if ($('comment_comment').value.length>max_length) {
            alert('The comment is longer than the maximum allowed '+max_length+' characters.');
            $('comment_comment').value=$('comment_comment').value.substring(0,max_length);
            return false;
        }*/
}

/*
    used for checking create user's customized links list at profile page.
*/
function validate_create_links_list(show_error_div) {
    disable_form(show_error_div,true);
    var errorhtml = "";
    if ( $("links_list_name").value.strip() == "" ) {
        errorhtml += error_list.blank_links_list_name + "#";
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top(show_error_div,get_error_list_html(errorhtml.split("#"),error_list.links_list_error_heading,''));
        disable_form(show_error_div,false);
        return false;
    }
}

/*
    used for checking when a user edits a customized links list title
*/
function validate_edit_external_list_title(show_error_div, id) {

    disable_form(show_error_div,true);
    var errorhtml = "";
    if ( $("links_list_name_" + id).value.strip() == "" ) {
        errorhtml += error_list.blank_links_list_name + "#";
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top(show_error_div,get_error_list_html(errorhtml.split("#"),error_list.links_list_error_heading,''));
        disable_form(show_error_div,false);
        return false;
    }
}

/*
    used for checking new blog addresses at profile page.
*/
function validate_external_link(show_error_div, postfix) {
    if (typeof(postfix) == "undefine") {
      postfix = "";
    } else {
      postfix = "_"+postfix;
    }
    disable_form(show_error_div+postfix,true);
    var errorhtml = "";
    if ( $("list_item_title"+postfix).value.strip() == "" ) {
        errorhtml += error_list.blank_list_item_title + "#";
    }
    if ( !validateurl($("list_item_url"+postfix).value) ) {
        errorhtml += error_list.invalid_list_item_url + "#";
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top(show_error_div+postfix,get_error_list_html(errorhtml.split("#"),error_list.links_list_error_heading,''));
        disable_form(show_error_div+postfix,false);
        return false;
    }
}


/*
    used for checking new blog addresses at profile page.
*/
function validate_external_blog(show_error_div) {
    disable_form(show_error_div,true);
    var errorhtml = "";
    if ( $("ext_blog_title").value.strip() == "" ) {
        errorhtml += error_list.external_blog_blank_title + "#";
    }
    if ( !validateurl($("ext_blog_url").value) ) {
        errorhtml += error_list.wrong_url + "#";
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top(show_error_div,get_error_div(errorhtml.split("#"),error_list.external_blog_error_heading,'width:250px;'));
        disable_form(show_error_div,false);
        return false;
    }
}

/*
    used for checking new blog addresses at profile page.
*/
function validate_favourite(show_error_div) {
    disable_form(show_error_div,true);
    var errorhtml = "";
    if ( $("favourite_title").value.strip() == "" ) {
        errorhtml += error_list.blank_favourite_title + "#";
    }
    if ( !validateurl($("favourite_url").value) ) {
        errorhtml += error_list.wrong_url + "#";
    }
    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        new Insertion.Top(show_error_div,get_error_div(errorhtml.split("#"),error_list.favourite_error_heading,'width:250px;'));
        disable_form(show_error_div,false);
        return false;
    }
}

/*
	this function used for validation stories and blogs beacuase we are using same page.
*/
function validate_add_news_story_form(story_full_content) {
    try
    {
        story_full_content = tinyMCE.get(story_full_content).getContent()
    }catch(ex)
    {
        log_exceptions("Method :- validate_add_news_story_form " + ex.message);
        return false;
    }
    try
    {
        disable_form('div_urls_rss_form',true);
        var errorhtml = "";
        tinyMCE.triggerSave();
        remove_previous_error_div();
        var action_type = $('action_type').value;
        var summary_visible= $('summary_row').style.display == "none";

        if ( $("story_title").value.strip() == "" && !summary_visible) {
            if(action_type == 'story')
            {
                errorhtml += error_list.blank_story_title + "#";
            }
            else
            {
                errorhtml += error_list.blank_blog_link_title + "#";
            }
        }

        if ( !validateurl($F("story_url")) ) {
            errorhtml += error_list.wrong_url + "#";
        }
        //geolocation of event/person/post event will be used
        //errorhtml += validate_geo_location('','optional');

        if ( errorhtml == "" && $('get_summary_or_submit').value == 'get_summary' )
        {
            remove_previous_error_div();
            oRequestHandlers[0].retrieve_url(tinyMCE, 'content', 'retrieve_url', 'story_full_content', $('story_url').value, $('page_type').value, $('page_id').value,action_type);

            disable_form('div_urls_rss_form',false);

            if(typeof($('getsummary').disable)!='undefined')
            {
                $('getsummary').disable();
            }
            else
            {
               $('getsummary').disabled = true;
            }
            return false;
        }else if (!summary_visible && story_full_content.length <= 0){
            errorhtml += error_list.blank_body + "#";
        }
        if ( errorhtml == "" ) {
            return true; //in case of successful validation
        } else {
            if(action_type == 'story')
            {
                new Insertion.Top('div_urls_rss_form',get_error_list_html(errorhtml.split("#"),error_list.url_feed_error_heading,''));
            }
            else
            {
                new Insertion.Top('div_urls_rss_form',get_error_list_html(errorhtml.split("#"),error_list.blog_link_error_heading,''));
            }
            disable_form('div_urls_rss_form',false);
            return false;
        }
    }catch(ex)
    {
        log_exceptions("Method :- validate_add_news_story_form exception block 2 " + ex.message);
    }
}

/*#########################################################################################################################
                                THIS CODE WILL BE REMOVED.
###########################################################################################################################*/
/*
    This method will be commented after doing benchmark stuff for
     the safari version 2.0.4
*/
/*var existing_time=null;*/
/*Used for benchmarking*/
/*function benchmark_method(message) {
    var start_time = new Date();
    if (existing_time==null) {
        existing_time = start_time.getTime();
        log_exceptions(message + existing_time);
    }else
    {
        log_exceptions(message +start_time.getTime() + "  time taken"  + (start_time.getTime()-existing_time));
        existing_time = null;
    }

}*/

//form validation for search form
/*
function validate_search_form(search_box_id) {
    var element = $(search_box_id);
    if (checkAlpha_50(element.value)) {
        return true;
    } else {

    }
     return false;
}
function checkAlpha_50(str) {
    var x = str;
    var filter  = /^([a-zA-Z ]){1,50}$/;
    if (filter.test(x)) return true;
    else return false;
}
*/

function launch_url(url){
    try
    {
        new Ajax.Request(url,
                         {
                             parameters:'',
                             asynchronous:true,
                             onLoading:function(){

                             }.bind(this),
                             onComplete: function(transport){

                             }.bind(this) //end Complete function
                         }
                        );
    } catch(ex){
        log_exceptions("Method :- launch_url " + ex.message);
    }
    return true;
}


/*
     This method is used to copy image contents into event contents form for creating event on profile page
*/

function event_from_image_content(image_index) {
    /*try
    {*/
    //tinyMCE.triggerSave();
    if (validate_image_upload_form()) {
        Element.hide('image_upload_div');
        //$('image_upload_div').hide();    //hide the image div
        copy_content_new_event('shared_image_title_' + image_index,'shared_image_desc_' + image_index,'geo_country_1','geo_state_1','geo_city_1','tag_list_' + image_index,'Image');
    }
    /*}catch(ex) {
        alert(ex.message);
    }*/
}

/*
     This method is used to copy video contents into event contents form for creating event on profile page
*/
function event_from_video_content(content_type) {
    /*try
    {*/
    //tinyMCE.triggerSave();
    if (validate_video_upload_form(content_type)) {
        Element.hide('video_upload_form');
        //$('video_upload_form').hide();    //hide the image div
        copy_content_new_event('shared_video_title_1','shared_video_desc_1','geo_country_1','geo_state_1','geo_city_1','tag_list_1','Video');
    }
    /*}catch(ex) {
        alert(ex.message);
    }*/
}


/*
     This method is used to copy blog contents into event contents for creating event on profile page
*/
function event_from_blog_content() {
    /*try
    {*/
    //tinyMCE.triggerSave();
	disable_form('blog_structure',true,'');
    if (validate_blog_form_in_lb()) {
		disable_form('edit_blog_form',false);
        Element.hide('blog_structure');
        //$('blog_structure').hide();  //hide blog div
        copy_content_new_event_new('blog_title','blog_full_content','geo_country_1','geo_state_1','geo_city_1','content_tag_list','Blog');
        //copy_content_new_event(cont_title,cont_desc,geo_country_index,geo_state,geo_city,tags)
        //tinyMCE.execInstanceCommand("mce_editor_0", "mceFocus");       not work in all FF
    }
	else
	{
		disable_form('blog_structure',false,'');
	}
    /*}catch(ex) {
        alert(ex.message);
    }*/
}

/* strip object & image tags */
function strip_video_img_tags(tiny_mce_content) {
    //tinyMCE.activeEditor.getContent()
  ScriptFragment = '<object[^>]*>([\\S\\s]*?)<\/object>';
  ScriptImageFragment = '<img[^>]*\/>';
  tiny_mce_content = tiny_mce_content.gsub(ScriptImageFragment,'');
    tiny_mce_content = tiny_mce_content.gsub(ScriptFragment,'');
    //tiny_mce_content = tinyMCE.activeEditor.getContent();
    return tiny_mce_content.gsub('<a [^>]*><img[^>]*\/>([\\S\\s]*?)<\/a>','');
    //return tiny_mce_content.replace(new RegExp(ScriptFragment), '')
}



/*
    This method is used to copy content from image,video and blog boxes(form) to create event box(form)
*/
function copy_content_new_event(cont_title,cont_desc,geo_country_index,geo_state,geo_city,tags,content_type) {
    Element.show('event_blog');
    //copy contents of blogs into creating user-event form
    title_val = $(cont_title).value;
    $('title').value = title_val;
    /*if (content_type != 'Blog') {
                $('summary').value = ($(cont_desc).value.stripTags()).gsub('&nbsp;',' ');
            }*/
    summary_text = $(cont_desc).value = strip_video_img_tags($(cont_desc).value).strip();
    //alert($(cont_desc).value);
    $('ref_blog_title').innerHTML = title_val;
    $('ref_blog_summary').innerHTML = summary_text;//.truncate(25);
    $('summary').value = summary_text;

    //$('event_geo_country_1').options[$('event_geo_country_1').selectedIndex].text=='USA'
    try
    {
        $('tag_list').value = $(tags).value;
        is_country_already_selected = false;
        if ($(geo_country_index).selectedIndex != -1 && $(geo_country_index).selectedIndex != 0) {
            if ($('event_geo_country_1').selectedIndex == $(geo_country_index).selectedIndex) {
                is_country_already_selected = true;
            } else {
                $('event_geo_country_1').selectedIndex = $(geo_country_index).selectedIndex;
            }
        }
        //$('event_geo_country_1').value = $('geo_country_1').value;

        if ($(geo_city).value.strip() != '') {
            $('event_geo_city_1').value = $(geo_city).value;
        }
        //copying states contents to create event form div.
        if ($(geo_state).selectedIndex != -1 &&  $(geo_state).selectedIndex != 0) {
            update_state_field = $('event_geo_state_1');
            current_state_field = $(geo_state);
            //copying contents of one selectbox to other.
            // innerHTML don't work  in IE
            if (!is_country_already_selected) {
                update_state_field.options.length = 0; //clearing previous contents of target dropdown.
                for(i=0; i<current_state_field.options.length; i++) {
                    var an_option = current_state_field.options[i];
                  var new_option = document.createElement("OPTION");
                    update_state_field.options.add(new_option);
                    try
                    {
                        //log_exceptions(an_option.text);
                        new_option.text = an_option.text;
                    }catch(e) {
                        log_exceptions("Method :- copy_content_new_event block 1 " + e.message);
                    }
                    //$('event_geo_state_1').innerHTML = $(geo_state).innerHTML
                    //alert($('event_geo_state_1').innerHTML);
                }
            }
            update_state_field.selectedIndex =     current_state_field.selectedIndex; //setting the selected index.
        }
        my_index = $(geo_country_index).selectedIndex;

        country_value = $(geo_country_index).options[my_index].text;

        if (country_value == "USA" || country_value == "United States of America") {
            /*
                        showing the state field
                    */
            Element.show('event_state_field_geo_1');
            $('event_geo_state_1').disabled = false;
        }
        $('submit').value='Publish';
        //alert("5");
        register_geo_location_with_id(1,'event_');
        //alert("6");
        create_event_loadEditor('summary');
        //alert("7");
        $('blog_reference').toggle();
    }catch(ex) {
        log_exceptions("Method :- copy_content_new_event block 2 " + ex.message);
    }

    //register auto location

    //setting focus to user-event summary
    //IE gives error when you focus a hidden filed.
    //$('summary').focus();
    //alert($('event_geo_state_1').innerHTML);

    //tinyMCE.activeEditor.focus();
}


/*
    This method is used to copy content from blog boxes(form) to create event box(form)
	with autocomple hidden fields instead of autocomplete drom down menu
*/
function copy_content_new_event_new(cont_title,cont_desc,geo_country,geo_state,geo_city,tags,content_type) {
    Element.show('event_blog');

    title_val = $(cont_title).value;
    $('title').value = title_val;

    summary_text = $(cont_desc).value = strip_video_img_tags($(cont_desc).value).strip();

    $('ref_blog_title').innerHTML = title_val;
    $('ref_blog_summary').innerHTML = summary_text;
    $('summary').value = summary_text;

    try
    {
		$('tag_list').value = $(tags).value;

		//copying country contents to create event form div.
		if ($(geo_country).value.strip() != '') {
			$('event_geo_country_1').value = $(geo_country).value;
		}

		//copying city contents to create event form div.
		if ($(geo_city).value.strip() != '') {
            $('event_geo_city_1').value = $(geo_city).value;
        }

		//copying states contents to create event form div.
		if ($(geo_state).value.strip() != '') {
            $('event_geo_state_1').value = $(geo_state).value;
        }

        $('submit').value='Publish';

        create_event_loadEditor('summary');

		$('blog_reference').toggle();
    }catch(ex) {
        log_exceptions("Method :- copy_content_new_event_new " + ex.message);
    }
}

// returns html for a new captcha image
function get_captcha(element_name) {
  var domain = location.protocol + "//" + location.host + ':' + location.port;
  return (new Ajax.Request(domain + '/main/change_captcha', {method:'get', asynchronous:false})).transport.responseText;
}




/*
This function used to create the share content form as its common on all pages and very difficult to change
on all place as when there is a new change we have to reflect it on all pages and json files.And editing json files for changes is really difficult.And old approach has one drawback is as same content with some modification is repeating on different pages like answers,questions,comments and events where share content is used. I think its the optimal solution to create the share content form on the fly and it will make our changes and page loading where more share content is very easy and faster.

parameters :: id - of the content
               content - type of the content
                page_url- type of the url
                div_to_insert- div in which content needed to insert

*/
function show_share_content_email_form(content_id, content_name, content_page_url, div_to_insert,mode, version, your_name, your_email) {
	try
	{
	var share_content_form_tempate = '';
    if (version == "new") {
        share_content_form_tempate = '<div class="siteEditForm" id="email-form-#{id}">' +
            '<div class="ajaxSpinner" id="answer_email_success_#{id}" style="display:none;">' +
            error_list.share_content_mail + '</div>' +
            '<div id="answer_email_form_error_#{id}" style="display:none;">' + error_list.captcha_error + '</div>' +
            '<div class="ajaxSpinner" style="display:none;" name="ans_form_spinner_display_#{id}" id="share_form_spinner_display_#{id}">' +
            '<p><img alt="wait..." src="/images/ajax/ajax-loader.gif"/></p>' +
            '<p>' + error_list.share_spinner_display + '</p>' +
            '</div>' +
            '<div class="clearFix">&nbsp;</div>' +
            '<div name="email_form_part_#{id}" id="email_form_part_#{id}">' +
            '<h3>Share With Your Friends</h3>' +
            '<p>Enter your friends email addresses separated by commas in the share with field below.</p>' +
            '<form onsubmit="new Ajax.Request(\'/content/share_content/#{id}\', {asynchronous:true, evalScripts:true, onComplete:function(request){/*if (dialogbox_response_eval(\'answer_email_form_error_#{id}\',\'error prohibited this content from being shared\',request.responseText,\'\'))*/if(request.responseText==\'{cancel:true}\'){hideDiv(\'share_form_spinner_display_#{id}\');Element.show(\'email-form-#{id}\');remove_previous_error_div();if(typeof(Recaptcha)!=\'undefined\'){remove_all_decendants(\'change_captcha_event_#{id}\');create_recaptcha(\'change_captcha_event_#{id}\');}$(\'answer_email_form_error_#{id}\').update(\'\');new Insertion.Top($(\'answer_email_form_error_#{id}\'),get_error_list_html([\''+ error_list.captcha_error+ '\'],\'' + error_list.wrong_email_heading+'\'));;Element.show(\'answer_email_form_error_#{id}\');showDiv(\'email_form_part_#{id}\');return false;}else{hideDiv(\'share_form_spinner_display_#{id}\');hideDiv(\'email_form_part_#{id}\');hideDiv(\'answer_email_form_error_#{id}\');Effect.Appear(\'answer_email_success_#{id}\', {duration:2.0});Effect.Fade(\'answer_email_success_#{id}\', {duration: 3.0});$(\'form_#{id}\').reset();}}, onLoading:function(request){hideDiv(\'answer_email_form_error_#{id}\');showDiv(\'share_form_spinner_display_#{id}\');hideDiv(\'email_form_part_#{id}\');}, parameters:Form.serialize(this)}); return false;"' +
            ' method="post" action="/content/share_content/#{id}" name="form_#{id}" id="form_#{id}">' +
            '<input type="hidden" value="#{content_type}" name="content_type" id="content_type" />' +
            '<input type="hidden" value="#{page_url}" name="page_url" id="page_url" />' +
            '<p><label>Share With:</label>' +
            '<input type="text" class="textInput" name="email_address_#{id}" id="email_address_#{id}" onclick="if(this.value==error_list.enter_email_address){this.value=\'\';}"></p>' +
            '<p><label>Your Name:</label>' +
            '<input type="text" class="textInput" name="your_name_#{id}" id="your_name_#{id}" value="' + your_name + '"></p>' +
            '<p><label>Your Email:</label>' +
            '<input type="text" class="textInput" name="your_email_#{id}" id="your_email_#{id}" value="' + your_email + '"></p>' +
            '<p><label>Your Comment:</label>' +
            '<td><textarea class="textArea" name="comment_#{id}" id="comment_#{id}"></textarea></p>' +
        '<div class="fieldSet reCaptcha"><label>Enter the text in the image:</label>' +
        '<div id="change_captcha_event_#{id}">#{captcha}</div>' +
        '</div>' +
            '<p class="siteEditFormButtons"><input type="image" ' +
			'src="/images/buttons/share.png" ' +
            'onclick="$(\'answer_email_success_#{id}\').hide();$(\'answer_email_form_error_#{id}\').hide();return validate_share_content_with_captcha($(\'email_address_#{id}\').value,$(\'your_name_#{id}\'),$(\'your_email_#{id}\'),this.form[\'captcha\'],\'answer_email_form_error_#{id}\',\'width:285px;\');" ' +
            'value="Share" name="share" id="share"/>' +
            '<input type="image" src="/images/buttons/cancel.gif" onclick="Element.hide(\'email-form-#{id}\');return false;" value="Cancel"/></p>' +
            '</form></div></div>';
    } else {
        share_content_form_tempate = '<div class="eventFormBox" id="email-form-#{id}"><div id="answer_email_success_#{id}" style="display:none;">' + error_list.share_content_mail + '</div><div id="answer_email_form_error_#{id}"></div><div style="padding: 10px;display:none;" name="ans_form_spinner_display_#{id}" id="share_form_spinner_display_#{id}"><center>' + error_list.share_spinner_display + '<img alt="wait..." src="/images/ajax/ajax-loader.gif"/><br/></center></div><span name="email_form_part_#{id}" id="email_form_part_#{id}"><br/><strong>' + error_list.share_content_multi_email + '</strong><br/><br/><form onsubmit="new Ajax.Request(\'/content/share_content/#{id}\', {asynchronous:true, evalScripts:true, onComplete:function(request){/*if (dialogbox_response_eval(\'answer_email_form_error_#{id}\',\'error prohibited this content from being shared\',request.responseText,\'\'))*/{hideDiv(\'share_form_spinner_display_#{id}\');hideDiv(\'email_form_part_#{id}\');$(\'answer_email_success_#{id}\').show();$(\'form_#{id}\').reset();}}, onLoading:function(request){hideDiv(\'answer_email_form_error_#{id}\');showDiv(\'share_form_spinner_display_#{id}\');hideDiv(\'email_form_part_#{id}\');}, parameters:Form.serialize(this)}); return false;" method="post" action="/content/share_content/#{id}" name="form_#{id}" id="form_#{id}"><table><tbody><tr><td>Share To</td><td><textarea class="interactive_ta" style="width: 530px;" name="email_address_#{id}" id="email_address_#{id}"></textarea><input type="hidden" value="#{content_type}" name="content_type" id="content_type" /><input type="hidden" value="#{page_url}" name="page_url" id="page_url" /></td></tr><tr><td>Your Name</td><td><input type="text" class="interactive_input" name="your_name_#{id}" id="your_name_#{id}" /></td></tr><tr><td>Your Email</td><td><input type="text" class="interactive_input" name="your_email_#{id}" id="your_email_#{id}"/></td></tr><tr><td>&nbsp;</td><td><input type="submit" onclick="$(\'answer_email_success_#{id}\').hide();return validate_share_content($(\'email_address_#{id}\').value,$(\'your_name_#{id}\'),$(\'your_email_#{id}\'),\'answer_email_form_error_#{id}\',\'width:285px;\');" value="Share" name="share" id="share"/><input type="button" onclick="Element.hide(\'email-form-#{id}\');return false;" value="Cancel"/></td></tr></tbody></table></form></span></div>';
    }

    //check that the created_content with given id is exist if exist then remove it first.
    var inserted_div = $('email-form-' + content_id);
    if (typeof(mode) != "undefined")
    {
        if(inserted_div != null ){
            inserted_div.hide();
        }
        return;
    }

	var temp_div_to_add = null;

	if (inserted_div != null)
	{

        if (!inserted_div.visible()) {

		  //inserted_div.show();
		  temp_div_to_add = inserted_div;
          /*
		  var myTemplate  = new Template(share_content_form_tempate);    // regenerate template to get new captcha image.
          var templateStr =  myTemplate.evaluate({captcha:get_captcha('event_share_button'),id:content_id,content_type:content_name,page_url:content_page_url});
          inserted_div.innerHTML = '';
		  inserted_div.innerHTML = templateStr;
		  */
        } else {
            inserted_div.hide();
			return;
        }
    }
	else
	{
        var div_to_add = $(div_to_insert);
        //substitue variable into tables
        //insert the template at the end of given content.
		if (div_to_add != null)
		{
			temp_div_to_add = div_to_add;
			/*
			var myTemplate  = new Template(share_content_form_tempate);
			var templateStr =  myTemplate.evaluate({captcha:get_captcha('event_share_button'),id:content_id,content_type:content_name,page_url:content_page_url});
			div_to_add.innerHTML = '';
			new Insertion.Bottom(div_to_add,templateStr);
			*/
		}
	}
	/* display proress bar element if its present on the page as we did not show it on mostly pages */
	var progress_bar_element = $(content_name.toLowerCase()+'_share_button');
	if(progress_bar_element != null)
	{
		progress_bar_element.show();
	}
    if(typeof(Recaptcha)=='undefined')
    {
	/* send ajax request and populate the template */
	new Ajax.Request('/main/change_captcha',{asynchronous:true,evalScripts:false,
					  onComplete:function(request)
					  {
						   var progress_bar_elem_name = $(content_name.toLowerCase() + '_share_button');
						   if( progress_bar_elem_name != null)
						   {
								progress_bar_elem_name.hide();
						   }
						   var myTemplate  = new Template(share_content_form_tempate);
						   //var templateStr =  myTemplate.evaluate({id:content_id,content_type:content_name,page_url:content_page_url});
                           var templateStr =  myTemplate.evaluate({captcha:request.responseText,id:content_id,content_type:content_name,page_url:content_page_url});
						   //temp_div_to_add.innerHTML = '';
						   temp_div_to_add.update(templateStr);
						   temp_div_to_add.show();
                           $('email_address_'+content_id).value = error_list.enter_email_address;
						   Element.show('email_form_part_'+content_id);
					 }.bind(this)
					 });

    }
    else
    {
        var progress_bar_elem_name = $(content_name.toLowerCase() + '_share_button');
        if( progress_bar_elem_name != null)
        {
            progress_bar_elem_name.hide();
        }
        var myTemplate  = new Template(share_content_form_tempate);
        var templateStr =  myTemplate.evaluate({
            id:content_id,
            content_type:content_name,
            page_url:content_page_url
        });
        //var templateStr =  myTemplate.evaluate({captcha:request.responseText,id:content_id,content_type:content_name,page_url:content_page_url});
        //temp_div_to_add.innerHTML = '';
        remove_all_decendants(temp_div_to_add);
        temp_div_to_add.update(templateStr);
        temp_div_to_add.show();
        $('email_address_'+content_id).value = error_list.enter_email_address;
        Element.show('email_form_part_'+content_id);
        create_recaptcha("change_captcha_event_"+content_id);
    }
}catch(ex)
	{
		log_exceptions("Method :-  show_share_content_email_form " + ex.message);
	}

	//$('event_share_button').hide();
	//get_box('captcha', 'change_captcha');
}

/*for links list entries*/
function delete_user_list_item(user_id,item_id,list_id) {
    new Ajax.Request('/user/delete_links_list_item/', {asynchronous:true, evalScripts:true,
                                                       onComplete:function(request){
														   Element.hide('edit_list_title_'+list_id);
                                                           //Element.hide('my_list_spinner_'+list_id);
                                                           //Element.show('external_link_operation_status_'+list_id);
                                                           oRequestHandlers[0].update('links_list', 'top');
                                                           //$('external_link_operation_status_'+list_id).update("<p>Record is deleted successfully</p>");
                                                       }, onLoading:function(request){
													   Element.show('external_link_operation_status_'+list_id);
                                                       $('external_link_operation_status_'+list_id).update("<p><img alt='deleting...' src='/images/ajax/ajax-loader.gif'/></p><p>Deleting the external link</p>");
                                                                                     },
                                                       parameters:'?profile_user_id=' + user_id + '&item_id='+ item_id
                                                      });
    return false;
}

/*deletes external list and all the items in the list*/
function delete_user_list(user_id,list_id) {
    new Ajax.Request('/user/delete_links_list/', {asynchronous:true, evalScripts:true,
                                                  onComplete:function(request){
                                                      Element.hide('edit_list_title_'+list_id);
													  //Element.hide('my_list_spinner_'+list_id);
                                                      //Element.show('external_link_operation_status_'+list_id);
                                                      oRequestHandlers[0].update('links_list', 'top');
                                                      //$('external_link_operation_status_'+list_id).update("<p>Record is deleted successfully</p>");
                                                  }, onLoading:function(request){                                                                                                                                                                                                                                                                                                       Element.show('external_link_operation_status_'+list_id);
                                                                                                                                                                                                                                                                                                                                                                                        $('external_link_operation_status_'+list_id).update("<p><img alt='deleting...' src='/images/ajax/ajax-loader.gif'/></p><p>Deleting the list</p>");
                                                                                },
                                                  parameters:'?profile_user_id=' + user_id + '&list_id='+ list_id
                                                 });
    return false;
}

/*for deleting blog entries*/
function delete_blog_entry(user_id,blog_id) {
    new Ajax.Request('/user/delete_external_blog/', {asynchronous:true, evalScripts:true,
                                                     onComplete:function(request){
                                                         Element.hide('my_blogs_spinner');
                                                         Element.show('external_blog_operation_status');
                                                         oRequestHandlers[0].update('external_blogs', 'top');
                                                         $('external_blog_operation_status').update("<p>Record is deleted successfully</p>");
                                                     }, onLoading:function(request){                                                                                                                                                                                                                                                                                                       Element.show('external_blog_operation_status');
                                                                                                                                                                                                                                                                                                                                                                                           $('external_blog_operation_status').update("<p><img alt='deleting...' src='/images/ajax/ajax-loader.gif'/></p><p>Deleting the blog</p>");
                                                                                   },
                                                     parameters:'?ext_blog_id=' + blog_id + '&profile_user_id='+ user_id
                                                    });
    return false;
}

/*for deleting favourite on profile page*/
function delete_favourite(user_id,favourite_id) {
    new Ajax.Request('/user/delete_favourite/', {asynchronous:true, evalScripts:true,
                                                 onComplete:function(request){
                                                     //Element.hide('my_blogs_spinner');
                                                     Element.show('favourites_operation_status');
                                                     oRequestHandlers[0].update('my_favourites', 'top');
                                                     $('favourites_operation_status').update("<p>Record is deleted successfully</p>");
                                                 }, onLoading:function(request){                                                                                                                                                                                                                                                                                                       Element.show('favourites_operation_status');
                                                                                                                                                                                                                                                                                                                                                                                       $('favourites_operation_status').update("<p><img alt='deleting...' src='/images/ajax/ajax-loader.gif'/></p><p>Deleting the favourite</p>");
                                                                               },
                                                 parameters:'?favourite_id=' + favourite_id + '&profile_user_id='+ user_id
                                                });
    return false;
}


function update_select_list(text,id){
    selectlist=document.getElementById(id);
    text = text.split(',');
    var j=0;
    count=selectlist.options.length;

    while(j<count) {
        selectlist.remove(j);
        j++;
    }
    selectlist.options.length=0;
    var i=0;
    var option = new Option();
    selectlist.options.add(option);
    option.text="";
    option.selected=true;
    while(i<text.length) {
        var option = new Option();
        selectlist.options.add(option);
        option.text=text[i];
        i++;
    }
}

/*
    This function is used for populate the state field when we select usa from country drop-down menu.
*/
function populate_state(country_field,fields_prefix,i,state_id,keep_city) {
	/*var keep_running = true;*/

	country_field = $(country_field);
    if (!keep_city) {
      $(fields_prefix + 'geo_city_' + i).value = '';
    }
    if (country_field.options[country_field.selectedIndex].text == 'USA') {
        Element.show(fields_prefix + 'state_field_geo_' + i);
        $(fields_prefix + 'geo_city_' + i).disabled = true;
        $(fields_prefix + 'geo_state_' + i).disabled = false;
		/*keep_running = false;*/
    } else {
        $(fields_prefix + 'geo_state_' + i).selectedIndex = 0;  // switch back to no state selected
        Element.hide(fields_prefix + 'state_field_geo_' + i);
        $(fields_prefix + 'geo_city_' + i).disabled=false;
    }
	/*if(keep_running)
	{
		setTimeout("populate_state('" + country_field.id + "','" + fields_prefix + "'," + i + ",'" + state_id + "');",100);
	}*/
	/*else
	{
		console.log('function is not running');
	}*/
}


// given a form and field id pattern, examine all country dropdowns and
// show/hide the state dropdowns. this does a lot of dubious string munging.
function populate_all_states(frm, fields_prefix) {
  for (var i=0; i<frm.elements.length; i++) {
    if (frm.elements[i]['id'].indexOf(fields_prefix+'geo_country') == 0) {
      var m = /(\d+)$/.exec(frm.elements[i]['id']); //extract index, eg the 9 in "foo_geo_country_9"
      if (m && m.length == 2) {
        populate_state(frm.elements[i], fields_prefix, m[1], '', true);
      }
    }
  }
}


/* CROSS-BROWSER EVENT HANDLER */
function addEvent(obj, evType, fn){
    if (obj.addEventListener){
        obj.addEventListener(evType, fn, true);
        return true;
    } else if (obj.attachEvent){
        var r = obj.attachEvent("on"+evType, fn);
        return r;
    } else {
        return false;
    }
}



/*loa javascript file on demand*/
function loadjscssfile(filename, filetype) {
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    } else if (filetype=="css") {
        //if filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref!="undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
}
/*
    function we use for splitting items
*/
function get_splited_item(item_to_split,div_character,index_to_return) {
    //check later whether requested index value is present or not.
    splitted_items_list = item_to_split.split(div_character);
    //alert(splitted_items_list[index_to_return]);
    if ( typeof(index_to_return) == 'undefined' ) {
        return splitted_items_list;
    } else {
        return splitted_items_list[index_to_return];
    }
}


/*Messaging JS*/
function SetAllCheckBoxes(FormName, FieldName, CheckValue) {
    if (!document.forms[FormName]) {
        return;
    }

    index = document.forms[FormName].elements["select1"].selectedIndex;

    //objCheckBoxes = document.forms[FormName].elements[FieldName];
    readCheckBoxes = document.forms[FormName].elements['read'];
    unreadCheckBoxes = document.forms[FormName].elements['unread'];

    //var countCheckBoxes = objCheckBoxes.length;
    if (index == 1) {
        readCheckValue = false;
        unreadCheckValue = false;
    } else if (index == 2) {
        readCheckValue = true;
        unreadCheckValue = false;
    } else if (index == 3) {
        readCheckValue = false;
        unreadCheckValue = true;
    } else if (index == 4) {
        readCheckValue = true;
        unreadCheckValue = true;
    }

    if (readCheckBoxes) {
        readCountCheckBoxes = readCheckBoxes.length;
        if (!readCountCheckBoxes) {
            readCheckBoxes.checked = readCheckValue;
        } else {
            // set the check value for all check boxes
            for(i = 0; i < readCountCheckBoxes; i++) {
                readCheckBoxes[i].checked = readCheckValue;
            }
        }
    }

    if (unreadCheckBoxes) {
        unreadCountCheckBoxes = unreadCheckBoxes.length;
        if (!unreadCountCheckBoxes)
            unreadCheckBoxes.checked = unreadCheckValue;
        else
            // set the check value for all check boxes
            for(i = 0; i < unreadCountCheckBoxes; i++) {
                unreadCheckBoxes[i].checked = unreadCheckValue;
            }
    }
}
function get_message_ids() {
    message_ids="";
    FormName = 'message_form';
    if (!document.forms[FormName]) {
        return message_ids;
    }

    readCheckBoxes = document.forms[FormName].elements['read'];
    unreadCheckBoxes = document.forms[FormName].elements['unread'];

    if (readCheckBoxes) {
        readCountCheckBoxes = readCheckBoxes.length;
        if (!readCountCheckBoxes) {
            if (readCheckBoxes.checked) {
                message_ids += readCheckBoxes.value + ",";
            }
        } else {
            for(i = 0; i < readCountCheckBoxes; i++) {
                if (readCheckBoxes[i].checked) {
                    message_ids += readCheckBoxes[i].value + ",";
                }
            }
        }
    }

    if (unreadCheckBoxes) {
        unreadCountCheckBoxes = unreadCheckBoxes.length;
        if (!unreadCountCheckBoxes) {
            if (unreadCheckBoxes.checked) {
                message_ids += unreadCheckBoxes.value + ",";
            }
        } else {
            for(i = 0; i < unreadCountCheckBoxes; i++) {
                if (unreadCheckBoxes[i].checked) {
                    message_ids += unreadCheckBoxes[i].value + ",";
                }
            }
        }
    }
    return message_ids;
}
/*Delete a single message onclick x_to_delete.gif*/
function DeleteMessage(message_id){
    new Ajax.Request('/message/delete_message_threads/', {asynchronous:true, evalScripts:true,
                                                          onComplete:function(request){
                                                              Element.hide('message_thread_'+message_id);
                                                          },
                                                          onLoading:function(request) {
                                                          },
                                                          parameters:'?message_ids=' + message_id
                                                         });
    return true;
}
/*Delete all selected messages*/
function DeleteMessages() {
    user_id = $('user_id').value;
    message_ids=get_message_ids();

    if (message_ids=="") {
        alert("no item to delete");
        return false;
    } else {
        new Ajax.Request('/message/delete_message_threads/', {asynchronous:true, evalScripts:true,
                                                              onComplete:function(request){
                                                                  messages = message_ids.split(",");
                                                                  for(i=0; i < messages.length; i++) {
                                                                      Element.hide('message_thread_'+messages[i]);
                                                                  }
                                                              }, onLoading:function(request) {
                                                              },
                                                              parameters:'?message_ids=' + message_ids + '&user_id='+ user_id
                                                             });
        return true;
    }

    return false;
}

function MarkAsUnread() {
    message_ids=get_message_ids();

    if (message_ids=="") {
        alert("No message selected");
        return false;
    } else {
        new Ajax.Request('/message/mark_as_unread/', {asynchronous:true, evalScripts:true,
                                                      onComplete:function(request){
                                                          messages = message_ids.split(",");
                                                          for(i=0; i < messages.length; i++) {
                                                              $('message_thread_'+messages[i]).addClassName('unread');
                                                          }
                                                      }, onLoading:function(request) {
                                                      },
                                                      parameters:'?message_ids=' + message_ids
                                                     });
        return true;
    }

    return false;
}



function MarkAsRead() {
    message_ids=get_message_ids();

    if (message_ids=="") {
        alert("No message selected");
        return false;
    } else {
        new Ajax.Request('/message/mark_as_read/', {asynchronous:true, evalScripts:true,
                                                    onComplete:function(request){
                                                        messages = message_ids.split(",");
                                                        for(i=0; i < messages.length; i++) {
                                                            $('message_thread_'+messages[i]).removeClassName('unread');
                                                        }
                                                    }, onLoading:function(request) {
                                                    },
                                                    parameters:'?message_ids=' + message_ids
                                                   });
        return true;
    }

    return false;
}

function validate_compose_message_form() {
    disable_form('compose_message',true);
    var errorhtml = "";

    if ($('message_user_name').value=="") {
        errorhtml += "You must specify recipient for this message.#";
    }

	if ($('message_subject').value.strip()=="") {
        errorhtml += "Subject cannot be empty.#";
    }

    my_values = get_tiny_mce_value('message_body');
    if ( my_values.text_value == '' || my_values.is_empty == true ) {
        errorhtml += error_list.blank_body + "#";
    }

    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        style = '';
        new Insertion.Top('compose_message',get_error_div(errorhtml.split("#")," error(s) prohibited this form from being saved",style,'errorExplanation_ans'));
        disable_form('compose_message',false);
        return false;
    }
}

function validate_reply_message_form() {
    disable_form('compose_message',true);
    var errorhtml = "";

    my_values = get_tiny_mce_value('message_body');
    if ( my_values.text_value == '' || my_values.is_empty == true ) {
        errorhtml += error_list.blank_body + "#";
    }

    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        style = '';
        new Insertion.Top('compose_message',get_error_div(errorhtml.split("#")," error(s) prohibited this form from being saved",style,'errorExplanation_ans'));
        disable_form('compose_message',false);
        return false;
    }
}

function validate_abuse_form(abuse_report_error_div) {
    disable_form(abuse_report_error_div,true);
    var errorhtml = "";

    if ($("abuse_reason_type").value == '') {
        errorhtml += "Please select abuse type." + "#";
    }

    if ( $("captcha").value == "" ) {
        errorhtml += "Enter text for Captcha image." + "#";
    }

    if ( errorhtml == "" ){
        return true; //in case of successful validation
    } else {
        new Insertion.Top(abuse_report_error_div, get_error_list_html(errorhtml.split("#"), 'error(s) prohibited this abuse report from sending',''));
        disable_form(abuse_report_error_div, false);
        return false;
    }
}

// new version for_abuse_report_form_ajax, supports multiple forms per page.
function val_abuse_form(error_div, frm) {
    disable_form(frm,true);
    var errors = [];

    if (frm.elements['abuse_reason_type'].value == '') {
        errors.push("Please select abuse type.");
    }

    if (frm.elements['abuse_reason_detail'].value == '') {
        errors.push("Please provide abuse detail.");
    }

    if(typeof(Recaptcha)!='undefined')
    {
        if(Recaptcha.get_response().strip()=='')
        {
            errors.push("Enter text for Captcha image.");
        }
    }
    else if(frm.elements['captcha'].value == ''){
        errors.push("Enter text for Captcha image.");
    }

    if ( errors.length == 0 ){
        frm.elements['page_url'].value = window.location.href;
        return true;
    } else {
        new Insertion.Top(error_div, get_error_list_html(errors, 'error(s) prohibited this abuse report from sending',''));
        disable_form(frm, false);
        return false;
    }
}




// javascript for msg_thread controller and assoc actions.
// given a form an an "action" (none, all, read, unread, etc)
// select all non, or select the checkboxes whose value matches a pattern.
// this involves some value-stuffing, unfortunately, like "1234-unread"
function checkboxer(frm, action) {
  var pat = new RegExp('\-'+action+'$');
  switch (action) {
    case '':
      return false;
      break;
    case 'all':
      var fn = function(v) {return true;};
      break;
    case 'none':
      var fn = function(v) {return false;};
      break;
    default:
      var fn = function(v) {return pat.match(v);};
  }
  for (var i=0; i<frm.elements.length; i++) {
    var e = frm.elements[i];
    if (e['type'] == 'checkbox') {
      e.checked = fn(e.value);
    }
  }
  return true;
}
// given a form, return values of all checked checkboxes. also has this value-stuffing thing.
function checkbox_values(frm, name) {
  var ret = [];
  for (var i=0; i<frm.elements.length; i++) {
    var e = frm.elements[i];
    if (e['type'] == 'checkbox' && e.checked) {
      ret.push([e, e.value.split('-')[0]]);
    }
  }
  return ret;
}

// given a form and an action, retrieve the affected ids and apply the action
function mark_messages(frm, action) {
  var ids = checkbox_values(frm);
  if (ids.length < 1) {
    return false;
  }

  if(action=='delete') {
	  $('message_mark_success').hide();
	  $('message_mark_progressbar').show();
  }

  var fn = null;
  switch (action) {
    case 'read':
    fn = function(o, el, val) {o.removeClassName('unread'); el.value=val+'-read';};
      break;
    case 'unread':
    fn = function(o, el, val) {o.addClassName('unread'); el.value=val+'-unread';};
      break;
    case 'delete':
    fn = function(o, el, val) {Element.hide(o);};
      break;
  }

  var callback = function(r) {
    for(var i=0; i < ids.length; i++) {
      fn($('message_thread_'+ids[i][1]), ids[i][0], ids[i][1]);
    }
  };

  new Ajax.Request('/msg_thread/mark', {
    asynchronous:false,
    evalScripts:true,
    onComplete: callback,
    parameters:'?ids=' + ids.join(',') + '&mark=' + action
  });

  if(action=='delete') {
	  $('message_mark_progressbar').hide();
	  $('message_mark_success').show();
  }

  return true;
}

function validate_msg_compose(frm) {
  var errs = [];
  if (frm.elements['recipient']['value'] == '') {
    errs.push("Please choose a recipient.");
  }
  if(frm.elements['subject'] && frm.elements['subject']['value'].length < 1) {
    errs.push('You need a subject.');
  }
  if(frm.elements['body'] && frm.elements['body']['value'].length < 1) {
   // errs.push('There is nothing in the message body. Cat got your tounge?');
   // for now, there are odd interactions with the textarea and tiny MCE.
  }
  if (errs.length > 0) {
    new Insertion.Top('compose_message', get_error_list_html(errs,"Whoops"));
    return false;
  }
  return true;
}


/*eof Messaging JS*/

function toggle_processing_div(disabled,div_to_hide) {
	try {

		if(typeof(div_to_hide) == 'undefined')
		{
			div_to_hide = 'div_processing_spinner';                      
		}
                if(!$(div_to_hide))
                {
                    return ;
                }
		if (disabled)
		{
			Element.show(div_to_hide);
		}
		else
		{
			Element.hide(div_to_hide);
		}
	} catch(ex) {
        log_exceptions("Method :- toggle_processing_div " + ex.message);
	}
}

function disable_form(div_id,disabled,hide_progress_bar,div_to_hide) {
    try{
        if(typeof(hide_progress_bar) == 'undefined')
        {
            toggle_processing_div(disabled,div_to_hide);
        }

        if (is_disable_img_button) {
            return;
        }

        //img_buttons = $(div_id).getElementsByClassName('imgButton');
        //green_buttons = $(div_id).getElementsByClassName('graphicBtnSmall');

        img_buttons = $(div_id).getElementsBySelector('button');

        try
        {
            for(i=0; i<img_buttons.length; i++)
            {
                    if (disabled)
                    {
                        if(typeof(img_buttons[i].disable)!='undefined')
                        {
                            img_buttons[i].disable();
                        }else
                        {
                            img_buttons[i].disabled = true;
                        }
                    }
                    else
                    {
                        if(typeof(img_buttons[i].enable)!='undefined')
                        {
                            img_buttons[i].enable();
                        }else
                        {
                            img_buttons[i].disabled = false;
                        }
                    }
            }
        }catch(ex)
        {
          
        }
        
        //for backward compatibility.
        img_buttons = $(div_id).getElementsByClassName('imgButton');
        try
        {
            for(i=0; i<img_buttons.length; i++)
            {
                    if (disabled)
                    {
                        if(typeof(img_buttons[i].disable)!='undefined')
                        {
                            img_buttons[i].disable();
                        }else
                        {
                            img_buttons[i].disabled = true;
                        }
                    }
                    else
                    {
                        if(typeof(img_buttons[i].enable)!='undefined')
                        {
                            img_buttons[i].enable();
                        }else
                        {
                            img_buttons[i].disabled = false;
                        }
                    }
            }
        }catch(ex)
        {

        }
        
    } catch (ex) {
        log_exceptions("Method :- disable_form " + ex.message);
    }
}

function disable_buttons(div_id) {
	if (is_disable_img_button) {
        return;
    }
    try {
        img_buttons = $(div_id).getElementsByClassName('imgButton');
        for(i=0; i<img_buttons.length; i++) {
			img_buttons[i].disable();
		}
    } catch(ex) {
		log_exceptions("Method :- disable_buttons " + ex.message);
    }
}


/*Drag and Drop JS*/
function move(id){
    var list = $('sortable_items').getElementsByTagName('li');
    var items = $A(list);
    items.each(function(it) {
        it.className = 'sortable_li';
    });
    Sortable.create("sortable_items", {onUpdate:function(){new Ajax.Request('/user/update_list_orders', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("sortable_items")})}, only:'sortable_li'});
    //disable_forms(id, 'move');
}
/*eof Drag and Drop JS*/

/*New Drag and Drop JS*/
function move_sortable_items(id){
    Sortable.create("sortable_items", {onUpdate:function(){new Ajax.Request('/user/update_list_orders', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("sortable_items")})}, tag:'div', only:'sortable_item'});
}
/*eof New Drag and Drop JS*/

/* ADDING SOME STRING FUNCTIONS */
function trim(str) {
	if (str == null || str.length == 0) {
		return "";
	}
	return str.replace(/^\s+|\s+$/g, "");
}
function isInteger(s){   
	var i;
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}
function stripCharsInBag(s) {   
	var i;
	var bag = "()- ";
    var returnString = "";
    for (i = 0; i < s.length; i++) {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
function validPhoneNumber(s){   
	return isInteger(stripCharsInBag(trim(s)));
}


/*
    This method is used to validate the form at tag_image(second screen of the multiple_upload images).
*/
function validate_tag_info(summary_boxes) {


    var summary_field_list = summary_boxes.split(',');
    var summary_index = 0;
    var errorhtml = "";
    var error_count = 0;
    var description = 0;

	var tinymce_value = get_tiny_mce_value('desc_' + summary_field_list[0],'');
	if(typeof(tinymce_value) != "object")
	{
		return false;
	}
    disable_form('multiple_images',true); //
	//summary_boxes.indexOf(",");

    for(summary_index=0;summary_index<summary_field_list.length; summary_index++) {
        remove_previous_error_div(summary_index+1);
        if (summary_field_list[summary_index] == '' ) {
            error_count += 1;
            continue;
        }
        if ( $("title_" + summary_field_list[summary_index]).value == "" ) {
            errorhtml += error_list.blank_title + "#";
        }

        description = get_tiny_mce_value('desc_' + summary_field_list[summary_index],'');
        if ( description.text_value == '' || description.is_empty == true ) {
            errorhtml += error_list.blank_description + "#";
        }

		ind = summary_field_list[summary_index];
		if ($("syndication_"+ind)!=null && $("syndication_"+ind).checked == 1){
			// check special location
			if ( $("syndication_location_"+ind).value=="" ){
				errorhtml += "You must specify the detailed location.#";
			}
			
			// check phone number 
			if ( $("syndication_phone_number_"+ind).value=="" ){
				errorhtml += "You must specify a contact telephone number of the format +1-555-555-5555.#";
			}
			
			// check phone number 
			if ( $("syndication_phone_number_"+ind).value!="" && (!validPhoneNumber($("syndication_phone_number_"+ind).value) || $("syndication_phone_number_"+ind).value.length>25) ){
				errorhtml += "You have specified an invalid phone number.#";
			}
			
			// check license
			if ( !$("license_"+ind+"_exclusive").checked && !$("license_"+ind+"_non_exclusive").checked ){
				errorhtml += "You must select a license under which you would like to syndicate your image or video.#";
			}
		}
		
		//no need to validate geolocation as it is removed from tag_images
        //errorhtml += validate_geo_location('','optional',(summary_index+1));

        if ( errorhtml == "" ) {
            error_count += 1;
            //return true;
        } else {
            //alert(errorhtml + ' ' + 'div_image_'+summary_field_list[summary_index]);
            new Insertion.Top('div_image_'+summary_field_list[summary_index],get_error_list_html(errorhtml.split("#"),error_list.multi_upload_image_heading,(summary_index+1)));
            errorhtml = '';
        }
    }


    if (error_count == summary_field_list.length) {
        return true;
    } else {
        disable_form('multiple_images',false);
        return false;
    }
}


/*
    This method is used to validate the form at tag_image(second screen of the multiple_upload images).
*/
function validate_video_tags(summary_boxes) {


    var summary_field_list = summary_boxes.split(',');
    var summary_index = 0;
    var errorhtml = "";
    var error_count = 0;
    var description = 0;

    summary_boxes.indexOf(",");

	var tinymce_value = get_tiny_mce_value('desc_' + summary_field_list[0],'');
	if(typeof(tinymce_value) != "object")
	{
		return false;
	}

	disable_form('multiple_video',true); //


    for(summary_index=0;summary_index<summary_field_list.length; summary_index++) {
        remove_previous_error_div(summary_index+1);
        if (summary_field_list[summary_index] == '' ) {
            error_count += 1;
            continue;
        }
        if ( $("title_" + summary_field_list[summary_index]).value == "" ) {
            errorhtml += error_list.blank_title + "#";
        }

        description = get_tiny_mce_value('desc_' + summary_field_list[summary_index],'');
        if ( description.text_value == '' || description.is_empty == true ) {
            errorhtml += error_list.blank_description + "#";
        }

		ind = summary_field_list[summary_index];
		if ($("syndication_"+ind)!=null && $("syndication_"+ind).checked == 1){
			// check special location
			if ( $("syndication_location_"+ind).value=="" ){
				errorhtml += "You must specify the detailed location.#";
			}
			
			// check phone number 
			if ( $("syndication_phone_number_"+ind).value=="" ){
				errorhtml += "You must specify a contact telephone number of the format +1-555-555-5555.#";
			}
			
			// check phone number 
			if ( $("syndication_phone_number_"+ind).value!="" && (!validPhoneNumber($("syndication_phone_number_"+ind).value) || $("syndication_phone_number_"+ind).value.length>25) ){
				errorhtml += "You have specified an invalid phone number.#";
			}
			
			// check license
			if ( !$("license_"+ind+"_exclusive").checked && !$("license_"+ind+"_non_exclusive").checked ){
				errorhtml += "You must select a license under which you would like to syndicate your image or video.#";
			}
		}
		
        //errorhtml += validate_geo_location('','optional',(summary_index+1));

        if ( errorhtml == "" ) {
            error_count += 1;
            //return true;
        } else {
            //alert(errorhtml + ' ' + 'div_image_'+summary_field_list[summary_index]);
            new Insertion.Top('div_video_'+summary_field_list[summary_index],get_error_list_html(errorhtml.split("#"),error_list.multi_upload_video_heading,'','',(summary_index+1)));
            errorhtml = '';
        }
    }


    if (error_count == summary_field_list.length) {
        return true;
    } else {
        disable_form('multiple_video',false);
        return false;
    }
}


function validate_youtube_vid_link(div_name) {
	disable_form(div_name,true);
    var errorhtml = "";
    remove_previous_error_div();
    if ($('youtube_link').value.gsub(" ","")=='') {
        errorhtml += "No Video selected. Please select a Video.#";
    }

    if ( errorhtml == "" ){
        //disable_form('div_video_upload_form');
        return true; //in case of successful validation
    } else {
        new Insertion.Top(div_name, get_error_list_html(errorhtml.split("#"),error_list.video_error_heading,''));
		disable_form(div_name,false);
        return false;
    }
}



function update_partial_event(my_country,my_city,my_state)
{
	try
	{
		//if geolocation is present and correct then send request for saving partial event
		var error_html = validate_geo_location('event_','required',1,my_country,my_city,my_state);
		//alert(error_html);
		remove_previous_error_div();
		if( error_html == "" || error_html == (error_list.blank_country + "#" + error_list.blank_city + "#"))
		{
			//alert('show saving location message at top, serialize form and send request.');
			get_tiny_mce_value('summary');
			//$('update_status').update('updating event');
			//$('update_status').show();
			new Ajax.Request('/event/update_event_partially/', {
			asynchronous:false,
			evalScripts:true,
			onComplete:function(request){
				//$('update_status').update('Event is updated successfully');
				//alert(request.responseText);
				return;
			},
			onLoading:function(request){
			   // Element.hide('div_update_event_form'+post_fix);
			   //Element.show('div_update_event_spinner'+post_fix);
			},
			parameters:$('event_create_form').serialize()});
			return true;
		}
		else if(error_html == (error_list.city_not_found + '#') || error_html == (error_list.blank_city + '#'))
		{

			new Insertion.Top('div_create_event',get_error_div(errorhtml.split("#")," error(s) prohibited this form from being saved",'510px','errorExplanation_ans'));
			return false;
		}
	}catch(ex)
	{
        log_exceptions("Method :- update_partial_event " + ex.message);
	}
	return false;
}

function event_duplication_check(event_id) {
	var domain = location.protocol + "//" + location.host;
	url = domain + "/event/check_duplicate";
	getVars = "event_id=" + event_id;

	new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
			onLoading:function() {
			},
			onComplete: function(transport){
				if (typeof(transport.responseText) == 'undefined' ||
					  transport.responseText == null || transport.responseText == "") {
					new Ajax.Request(domain + "/event/process_new_event", {parameters:getVars+"&render_template=yes", asynchronous:false});
					transport.responseText = "new_event";
				}

				if (transport.responseText == "new_event") {
					url = domain + "/contributed-news/" + event_id;
					//window.location = url;
					Element.hide('new_event_created');
					Element.show('new_event_created_2');

					setTimeout('document.new_event_created_2.submit();',400);
				} else {
					$('duplicate_screen').hide();
					$('similar_events').update(transport.responseText);
					url = domain + "/event/show_similar_events";
					//window.location = url;
				}
			}
	});
}


function event_tag_suggestion(event_id) {
	var domain = location.protocol + "//" + location.host;
	url = domain + "/event/check_suggested_tags";
	getVars = "event_id=" + event_id;
	new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
			onLoading:function() {
			},
			onComplete: function(transport){
				var rt = transport.responseText;
				
				if (rt == "new_event" || typeof(rt) == "undefined" || rt.length==0) {
					url = domain + "/event/post_create_event";
					Element.hide('ts_new_event_created');
					Element.show('ts_new_event_created_2');
					setTimeout('document.ts_new_event_created_2.submit();',400);
				} else {
					
					$('duplicate_screen').hide();
					$('duplicate_screen').update('');
					$('tag_suggestions').update(transport.responseText);
					url = domain + "/event/copyright_violation";
				}
			}
	});
}


function event_copyright_check(event_id) {
	var domain = location.protocol + "//" + location.host;
	url = domain + "/event/check_copyright";
	getVars = "event_id=" + event_id;

	new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
			onLoading:function() {
			},
			onComplete: function(transport){
				if (transport.responseText == "new_event") {
					url = domain + "/event/post_create_event";
					Element.hide('cr_new_event_created');
					Element.show('cr_new_event_created_2');

					setTimeout('document.cr_new_event_created_2.submit();',400);
				} else {
					$('duplicate_screen').hide();
					$('duplicate_screen').update('');
					$('similar_events').update(transport.responseText);
					url = domain + "/event/copyright_violation";
				}
			}
	});
}


function save_new_event(event_id) {
	var domain = location.protocol + "//" + location.host;
	url = domain + "/event/save_new_event";
	getVars = "event_id=" + event_id;

	new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
			onLoading:function() {
			},
			onComplete: function(transport){
				response_data = eval("("+transport.responseText+")");
				url = domain + "/contributed-news/" + response_data.event_id + "?clear_cache=true";
				setTimeout("window.location = url",3000);
			}
	});
}


function attach_contributions(event_id) {
	var domain = location.protocol + "//" + location.host;
	url = domain + "/event/attach_contributions";
	getVars = "event_id=" + event_id;

	new Ajax.Request(this.url, {parameters:getVars, asynchronous:false,
			onLoading:function() {
			},
			onComplete: function(transport){
				response_data = eval("("+transport.responseText+")");
				url = domain + "/contributed-news/" + response_data.event_id;
				document.attach_form.submit();
			}
	});
}

function buildErrors(options) {
  var wrapper = new Element('div', { id: 'errorList', className: 'errorList '});
  var inner = new Element('div', { className: 'errorListInner' });
  var h5 = new Element('h5').update(options.title);
  var ul = new Element('ul');
  options.errors.each(function(error){
    ul.insert(new Element('li').update(error))
  });
  inner.insert(h5).insert(ul);
  wrapper.insert(inner);
  return wrapper;
}

// this trumps submit_comment_form
var commentPosting = false;
function submitComment(something) {
  if (commentPosting) return false;
  $('commentError').hide();
  var f;
  
  if (Object.isElement(something)) {
    f = something;
  } else {
    Event.stop(something);
    f = Event.element(something);
  }
  var serialization = f.serialize(true);
  var commentId = $F('comment_id');
  var commentText = $F('comment_comment');
  if (commentText == null || commentText.replace(/\s/g,"") == "") {

    $('commentError').show();

    var options = {
        'title': 'The following error(s) prohibited this Comment from being saved',
        'errors': ['Comment cannot be blank']
    };

    $('commentError' + commentId).update(buildErrors(options));
    return false;
  }else if (commentText.split(" ").length < 4){
	  $('commentError').show();

	    var options = {
	        'title': 'The following error(s) prohibited this Comment from being saved',
	        'errors': ['Your comment is too short. Express yourself!']
	    };

	    $('commentError' + commentId).update(buildErrors(options));
	    return false;
  }
  var path = commentId.blank() ? '/comments' : '/comments/'+commentId;
  if (serialization['recaptcha_challenge_field']) path = '/comments/'+serialization['comment[id]']+'/ham';
  new Ajax.Request(path, {
    method: commentId.blank() ? 'post' : 'put',
    parameters: serialization,
    onCreate: function() {
      commentPosting = true;
      $('form_spinner_display').update($F('save_comment_msg'));
      $('form_spinner_display').show();
      $$('.errorList').invoke('remove');
    },
    onFailure: function(transport) {
      $('form_spinner_display').hide();
      showLoginBox($('postcomment'), submitComment.curry(f));
    }, 
    onComplete: function(transport) {
      commentPosting = false;
      $('form_spinner_display').hide();
    }
  })

  return false;
}

// carlos 9 july 2008
// it's time to start movng these godawful inlines into functions
function submit_comment_form(id,content_type,update_all_list) {
	//alert(" in submit_comment_form , id: "+ id );
	try{
  	if(typeof(id)=='undefined') { // this will be executed when editing comments from user profile
  		id = $('commentable_id').value;
  	}
	new Ajax.Request(
        '/main/save_comment/' + id,
        {asynchronous:true,
        evalScripts:true,
        onComplete:function(request){
            try
            {
            	//alert(" in submit_comment_form.onComplete response text " + request.responseText);
            						if($('popupLoginBox')){
								        	$('popupLoginBox').hide();
								        }

                        dialog_response = eval(request.responseText);
                        is_defined_response = true;
                        if(typeof(dialog_response)=='undefined' || dialog_response == null) {
                        	is_defined_response = false;
                        }

                        if(is_defined_response && dialogbox_response_eval('div_comment_form','error prohibited this Comment from being saved ',request.responseText,'')) {
                            RedBox.close();
                            oRequestHandlers[0].clearCache();
                            if(typeof(update_all_list)=='undefined')
                            {
                                update_all_list = true;
                            }
                            if(typeof(content_type)=='undefined')
                            {
                                content_type = 	'content';
                            }
                            oRequestHandlers[0].addVars='content_id='+id+'&content_type='+content_type;
                            oRequestHandlers[0].update('comments');
                            if(update_all_list == true)
                            {
                                oRequestHandlers[0].clearCache();
                                oRequestHandlers[0].update('contributions');
                            }
                        } else {
                            $('form_table').style.display='';
                            $('form_spinner_display').style.display='none';
                        }

                        // add anchor and reload page
                        if (is_defined_response && dialog_response.status =="ok") {
                            var base_url = ""+window.location;
                            if (base_url.indexOf("#") != -1) {
                                base_url = base_url.substring(0,base_url.indexOf("#"));
                            }

                            $('form_table').style.display='';

                            var comment_count = parseInt($('comment_count').innerHTML);

                            if (true) {

                                if ($('editornew').value != "edit") {
                                    comment_count = comment_count + 1;
                                    $('comment_count').innerHTML = comment_count;

                                    $('comments_span').innerHTML = "Comments: " + comment_count;
                                    if ($('expand_comment') != null) {
                                        $('expand_comment').innerHTML = "Comments: " + comment_count;
                                    }

                                    var refDiv = null;

                                    parent_id = $('comment_parent_id').value;
                                    if (typeof(parent_id) != "undefined" && parent_id != "") {
                                        refDiv = $("li_" + parent_id);
                                    } else {
                                        refDiv = $("dummy_div");
                                    }

                                    var newDiv = document.createElement("div");
                                    newDiv.innerHTML = "&nbsp;";
                                    newDiv.setAttribute("id", "new_comment_" + dialog_response.parent_obj_id);
                                    refDiv.appendChild(newDiv);
                                }

                                $('q_a_c_id').value = dialog_response.parent_obj_id;

                                render_comment();
                                commentPost();

                            }
                        }
                    }catch(ex)
                    {
                        log_exceptions("Method :- save_comment" + ex.message);
                    }
        },
        onLoading:function(request){
          Element.hide('form_table');
          Element.show('form_spinner_display');
          if ($('save_comment_msg') != null && typeof($('save_comment_msg')) != "undefined") {
          	$('comment_msg').innerHTML = $('save_comment_msg').value;
          }
        },
        parameters:'comment[type]='+encodeURIComponent($('comment_type').value.escapeHTML())+'&comment[comment]='+encodeURIComponent($('comment_comment').value)+'&comment[content_id]='+encodeURIComponent($('comment_content_id').value)+'&q_a_c_id='+$('q_a_c_id').value+'&editornew='+$('editornew').value+'&parent[root]='+$('parent_root').value.escapeHTML()+'&comment[parent_id]='+$('comment_parent_id').value.escapeHTML()
        });

  } catch(e)
  {
      log_exceptions("Method :- submit_comment_form " + e.message);
  }
  return false;
};

function save_comment_form_params() {
  try{
	new Ajax.Request(
        '/main/save_comment_form_params',
        {asynchronous:true,
        onComplete:function(request){
        },
        parameters:'comment[type]='+encodeURIComponent($('comment_type').value.escapeHTML())+'&comment[comment]='+encodeURIComponent($('comment_comment').value)+'&comment[content_id]='+encodeURIComponent($('comment_content_id').value)+'&q_a_c_id='+$('q_a_c_id').value+'&editornew='+$('editornew').value+'&parent[root]='+$('parent_root').value.escapeHTML()+'&comment[parent_id]='+$('comment_parent_id').value.escapeHTML()
        });

  } catch(e)
  {
      log_exceptions("Method :-  save_comment_form_params " + e.message);
  }
  return false;
};


function delete_comment(id,content_type,update_all_lists) {
  try{
    new Ajax.Request(
        '/main/delete_comment/' + id,
        {asynchronous:true,
        evalScripts:true,
        onComplete:function(request){

            //if(dialogbox_response_eval('div_comment_form','error prohibited this Comment from being saved ',request.responseText,'')) {
				if(typeof(content_type) == 'undefined')
				{
					content_type = 'content';
				}
                if(typeof(update_all_lists) == 'undefined')
				{
					update_all_lists = true;
				}

				oRequestHandlers[0].clearCache();
                oRequestHandlers[0].addVars='content_id='+id+'&content_type='+content_type;
                oRequestHandlers[0].update('comments');

				if(update_all_lists)
				{
					oRequestHandlers[0].clearCache();
                	oRequestHandlers[0].update('contributions');
				}
            //} else {
            //    $('form_table').style.display='';
            //    $('form_spinner_display').style.display='none';
            //}
            window.location.reload();
        },
        onLoading:function(request){
          //Element.hide('form_table');
          Element.show('form_spinner_display');
          if ($('delete_comment_msg') != null && typeof($('delete_comment_msg')) != "undefined") {
          	 $('comment_msg').innerHTML = $('delete_comment_msg').value;
          }

        },
        parameters:'q_a_c_id='+ $('q_a_c_id').value+'&comment[type]='+encodeURIComponent($('comment_type').value.escapeHTML())
        });
  } catch(e) {
      log_exceptions("Method :- delete_comment " + e.message);
  }
  return false;
};


function rateit(obj,id,sign,rateable_type) {
    var direction = sign==1 ? 'up' : 'down';
    if(rateWait(obj, id, direction)) {
        new Ajax.Request('/save_rate/'+id,
          {
            asynchronous:true,
            evalScripts:true,
            onComplete:function(request){

				if (rateable_type=="Event" || rateable_type=="Person")
				{
					rates = request.responseText.split("-");
					$('rateUp'+id).innerHTML=rates[0];
					$('rateDown'+id).innerHTML=rates[1];
				}
                rateCallback(request, direction, id);
            },
            parameters:'?rateable_type='+rateable_type+'&value=' + sign
          });
    }
    return false;
}

function save_rateit_session(obj,id,sign,rateable_type) {
    new Ajax.Request('/save_rate_session/' + rateable_type + '/' + id + '/' + sign,
    {
      asynchronous:true,
      evalScripts:true
    });
    return false;
}


//odd that it does not have a 'type' like event, person, etc.
function clkstrm(anchor_obj, my_id) {
    new Ajax.Request('/main/save_external_clickstream/'+my_id+"?u="+escape(anchor_obj.href), {asynchronous:true});
}

function tog_abuse_form(content_id, content_type, subtype) {
    try
    {
        var my_error_list = $('abused-form-'+ content_id + '_abuse_report_error');
        var content_to_update = 'report-form-'+subtype+'-'+content_id;
        if(subtype === '')
        {
            content_to_update  = 'report-form-'+content_type+'-'+content_id;
        }

        if(my_error_list)
        {
            my_error_list.remove();
        }

        if($('abused-form-'+content_id)==null || $('abused-form-'+content_id).visible())
        {
            //alert('form should be toggled');
            Element.toggle(content_to_update);
            var my_report_id = $(content_to_update);
            if(!my_report_id.visible())
            {
                my_report_id.update('');
                try {
                    $('flagEventLink').className = 'reportAbuse';

                } catch (e) {
                    log_exceptions("Method :- tog_abuse_form " + e.message);
                }
                return;
            }
        }
        /*else
        {
            $(content_to_update).show();
        }*/


        /*
            spinner dont work properly due to ajax blocker request
        */
        new Ajax.Request('/event/abused/'+content_id+'?atype='+content_type+'&subtype='+subtype, {asynchronous:true, evalScripts:true,
                                                           onComplete:function(request){
                                                               try
                                                               {
                                                                 //$(content_to_update).update('');
                                                                 remove_all_decendants(content_to_update);
                                                                 $(content_to_update).show();

                                                                //$(content_to_update).update(request.responseText);
                                                                new Insertion.Bottom(content_to_update, request.responseText);
                                                                var change_captcha_id = "change_captcha_" + content_id;
                                                                create_recaptcha(change_captcha_id);
                                                                //Recaptcha.create(recaptcha_pub_key, change_captcha_id,{theme: "red",callback: Recaptcha.focus_response_field});
                                                               $('flagEventLink').className = 'reportAbuse';
                                                               }catch(ex)
                                                               {
                                                                log_exceptions("Callback of /event/abused/ call" + ex.message)
                                                               }
                                                           }
                                                          });
        /*
        new Ajax.Updater(
          content_to_update,
          '/event/abused/'+content_id+'?atype='+content_type+'&subtype='+subtype, {asynchronous:false, evalScripts:true}
        );
        try{
            $('flagEventLink').className = 'reportAbuse';

        } catch (e) {}
        */
    }catch(ex)
    {
       log_exceptions("Method :- tog_abuse_form " + ex.message);
    }
}

function radio_checked(nlist) {
  if (!nlist.length) { return nlist.checked; }
  for (var i=0; i<nlist.length; i++) {
    if (nlist[i].checked) { return true; }
  }
  return false;
}

function validateSEForm() {
  try {
    var submit_type = document.getElementById("submitType").value;
   	if (submit_type == "ExistingEvent" && !radio_checked(document.getElementById('similarEventForm')['existing_id'])) {
      alert('Please select an existing event');
      return false;
   	} else {
   	  return true;
   	}
  } catch(ex) {
	log_exceptions("Method :- validateSEForm "+ ex.message);
  }
}

//at some point you have to start wondering whether it's good programming practice to copy paste copy paste copy paste...
function check_url_redirect(page_name) {
	//var my_page_url = location.protocol + "//" + location.host + location.pathname;
	/* location.href gives complete url including hash & location search.*/
	var my_page_url = location.href;
	if(my_page_url.indexOf(page_name) == 0)
	{
		return true;
	}
	else
	{
		window.location = location.protocol + "//" + location.host + "/post_event";
		return false;
	}
}

/*
	we are using this method at similar event page.
*/
function submit_form()
{
	document.similarEventForm.submit();
	return false;
}

/*
	method to delete contents from News/People tabs by admin
*/
function delete_content_item(content_id, content_type, div_to_refresh)
{
	if (confirm_submit("Are you sure you want to delete this content?")) {
        new Ajax.Request('/content/delete_content_item/'+content_id+'?content_type='+content_type, {asynchronous:true, evalScripts:true, onComplete:function(request){
																																							 			oRequestHandlers[0].clearCache();
            oRequestHandlers[0].update(div_to_refresh);
        }
        });
    }
}

/*
	method to delete contents from News/People tabs by admin
*/
function change_content_item_status(content_id, content_type, div_to_refresh, status, event_person_id)
{
	if (confirm_submit("Are you sure you want to " + status + " this content?")) {

        new Ajax.Request('/content/delete_content_item/'+content_id+'?content_type='+content_type+'&status='+status+'&event_person_id='+event_person_id, {asynchronous:true, evalScripts:true, onComplete:function(request){
																																							 			oRequestHandlers[0].clearCache();
            //oRequestHandlers[0].update(div_to_refresh);
            window.location.reload();
        }
        });
    }
}

/*
	method to delete related events from News/People related events list by admin
*/
function change_related_event_status(event_person_id, related_event_id, status, related_event_type)
{
	if (confirm_submit("Are you sure you want to hide this related event?")) {

        new Ajax.Request('/content/delete_related_event?event_person_id='+event_person_id+'&related_event_id='+related_event_id+'&status='+status+'&related_event_type='+related_event_type, {asynchronous:true, evalScripts:true, onComplete:function(request){																																							 			oRequestHandlers[0].clearCache();
            window.location.reload();
        }
        });
    }
}

/*
	method to set people page
*/
function change_person_image(person_id, image_id)
{
	change_event_image(person_id, image_id, 'Person');
}
/*
method to set event image or people image
*/
function change_event_image(event_id, img_id,entity_type)
{
	if(typeof(entity_type) == 'undefined')
	{
		entity_type = 'Event';
	}

	if (confirm_submit("Are you sure you want to change the " + entity_type +" image?")) {

        new Ajax.Request('/set_thumbnail_id_via_list_view/'+entity_type.toLowerCase()+'/' + event_id + '/' + img_id, {asynchronous:true, evalScripts:true, onComplete:function(request){																																							 			oRequestHandlers[0].clearCache();
            oRequestHandlers[0].clearCache();
            window.location.reload();
        }
        });
    }
}


/* we are using this method for burying event/person */
function bury_event_person(entity_type, id,current_page,type,category,filter)
{
     new Effect.Fade('form_spinner_display_fade_'+id, {duration:0.0, from:1.0, to:0.9});
     new Ajax.Request(
        '/main/bury_event_people/',
        {asynchronous:true,
        evalScripts:true,
        onComplete:function(request){
                Element.hide('form_spinner_display_'+id);
				//oRequestHandlers[0].clearCache();
                //if(entity_type == 'event')
				//{
				//	entity_type += 's';
				//}
				//oRequestHandlers[0].setParameters(current_page,type,category,filter);
				//oRequestHandlers[0].update(entity_type,'top');
				window.location.reload();
        },
        onLoading:function(request){
			Element.show('form_spinner_display_'+id);
          //Element.hide('form_table');
         // Element.show('form_spinner_display');
        },
        parameters:'id='+ id+'&type='+entity_type
        });

}

/*check whether tinymce is loaded or not*/
function is_tiny_mce_loaded(summary_field_name)
{
	var ret_val = false;
	try
	{
		get_tiny_mce_value(summary_field_name);
		ret_val = true;
	}catch(ex)
	{
        log_exceptions("Method :- is_tiny_mce_loaded " + ex.message);
	}
	return ret_val;
}

function validate_bulk_email_form(div_to_add,optional_width,post_fix) {
    remove_previous_error_div();

    if (typeof(post_fix) == 'undefined') {
        post_fix='';
    }

    var errorhtml = "";

    if ($('subject'+post_fix).value.strip()=="") {
        errorhtml += "Subject cannot be empty.#";
    }

    my_values = get_tiny_mce_value('message'+post_fix);
    if ( my_values.text_value == '' || my_values.is_empty == true ) {
        errorhtml += error_list.blank_body + "#";
    }

    if ( errorhtml == "" ) {
        return true; //in case of successful validation
    } else {
        style = '';
        if (typeof optional_width != "undefined") {
            style = optional_width;
        }

        new Insertion.Top(div_to_add,get_error_list_html(errorhtml.split("#")," error(s) prohibited this form from being saved",style,'errorExplanation_ans'));
        return false;
    }
}

// set the event landing page cookie for redirects
function set_redirect_cookie(){
	setCookie('event_landing_page','true');
}

function get_abuse_report_ids() {
    checkbox_ids="";
    FormName = 'abuse_form';
    if (!document.forms[FormName]) {
        return checkbox_ids;
    }

    abuse_report_boxes = document.forms[FormName].elements['abuse_report'];

    if (abuse_report_boxes) {
        abuseCountCheckBoxes = abuse_report_boxes.length;
        if (!abuseCountCheckBoxes) {
            if (abuse_report_boxes.checked) {
                checkbox_ids += abuse_report_boxes.value + ",";
				 abuse_report_boxes.checked = false;
            }
        } else {
            for(i = 0; i < abuseCountCheckBoxes; i++) {
                if (abuse_report_boxes[i].checked) {
                    checkbox_ids += abuse_report_boxes[i].value + ",";
					abuse_report_boxes[i].checked = false;
                }
            }
        }
    }
    return checkbox_ids;
}


function change_abuse_report_status(status, abuse_report_ids) {
	if(abuse_report_ids=="")
		abuse_report_ids = get_abuse_report_ids();

	if (abuse_report_ids=="") {
        alert("No abuse report selected");
        return false;
    } else {
		new Ajax.Request('/admin/change_abuse_report_status'+'?status='+status+'&abuse_report_ids=' + abuse_report_ids, {asynchronous:true, evalScripts:true,
			onComplete:function(request){
				window.location.reload();
			},
			onLoading:function(request) {} }
		);
        return true;
    }
    return false;
}

function submit_resolution_comment_form() {
	try{
		new Ajax.Request(
			'/admin/save_resolution_comment',
			{
				asynchronous:true,
				evalScripts:true,
				onComplete:function(request){

					if(dialogbox_response_eval('div_comment_form','error prohibited this Comment from being saved ',request.responseText,'')) {
						RedBox.close();
						oRequestHandlers[0].clearCache();
						window.location.reload();
					} else {
						$('form_table').style.display='';
						$('form_spinner_display').style.display='none';
					}
				},
				onLoading:function(request) {
					Element.hide('form_table');
					Element.show('form_spinner_display');
				},
				parameters:'resolution_comment='+$('resolution_comment').value+'&report_id='+$('report_id').value
			}
		);
	} catch(e) {
		log_exceptions("Method :- submit_resolution_comment_form " + e.message);
	}
	return false;
};

// given a form object, a string prefix, and an example form element,
// set the values of all form elements whose id matches the string
// prefix with the value (or selectedIndex) of the example element,
// if and only if the target element's value is currently null. and
// the example element's value is not null.
// todo: this function may better be served using DOM or CSS selectors
// from prototype, YUI, etc. For our purposes right now this is ok.
function prefill_form_fields(frm, prefix, el) {
    for (var i=0; i<frm.elements.length; i++) {
       if (frm.elements[i].id.indexOf(prefix) == 0 && frm.elements[i].id != el.id) {
           if(el['selectedIndex'] || el['selectedIndex'] == 0) {
                if (!frm.elements[i].selectedIndex) {
                    frm.elements[i].selectedIndex = el.selectedIndex;
                }
            } else if (el.value && el.value != '') {
                if (!frm.elements[i].value) {
                    frm.elements[i].value = el.value;
                }
            }
       }
    }
}


function update_element_fade(element_name,content)
{
	tag_element = $(element_name);
	tag_element.update(content);
	tag_element.show();
	Effect.Fade(element_name, {duration: 5.0});
}

/* this function is used to get the list of suggested tags from backend system according to the title,summary,country,city and category.*/
function load_backend_suggested_tags(post_fix)
{
	try
	{
		var title=summary=country=city=category_id='';
		var error_msg = ""
		//if title/summary is missing then prompt user for entering required information
		title = $('title'+post_fix).value.strip();
		if (title == "") {
			error_msg += "Title cannot be empty.<br/>"
			//alert("Title cannot be empty.");

		}

		my_values = get_tiny_mce_value('summary'+post_fix);
		if(typeof(my_values) != "object")
		{
			return false;
		}

		//disable_form(div_to_add,true);
		summary = my_values.text_value;
		if (summary == '' || my_values.is_empty == true) {
			error_msg += error_list.blank_body;
			//alert(error_list.blank_body);

		}


		if(error_msg != "")
		{
			update_element_fade('tag_list_error',error_msg);
			return;
		}

		category_id = $('category').value;
		/*getting country.*/
		if($('event_geo_country_1').selectedIndex != 0)
		{
			country = $('event_geo_country_1').value;
			/*just getting country not verifying city name*/
			if($('event_geo_city_1').value != '')
			{
				city = $('event_geo_city_1').value;
			}
		}

		//send ajax request to load the suggested tags into tags field.
		new Ajax.Request('/event/get_suggested_tags/', {
				asynchronous:true,
				evalScripts:true,
				onComplete:function(request){
					//hide the progress bar message
					//append the tag_list input field.
					$('load_tags_progress_bar').hide();
					if(request.responseText.strip() == "")
					{
						update_element_fade('tag_list_error',error_list.no_tag_found);
						return;
					}
					else
					{
						$('tag_list').value = request.responseText;
					}
					return;
				},
				onLoading:function(request){
					//show progress message of loading tags
					$('load_tags_progress_bar').show();
				},
				parameters:'title='+encodeURIComponent(title)+'&summary='+encodeURIComponent(summary)+'&country='+encodeURIComponent(country)+'&city='+encodeURIComponent(city)+'&category_id='+category_id+'&tag_list='+$('tag_list').value});
				return true;
	}catch(ex)
	{
		log_exceptions("Method :- load_backend_suggested_tags " + ex.message);
	}
}

/*This function is used to add bookmarks to Content, Event, Person, User, and UserSubmittedContent*/
function add_bookmark(bookmarkable_id, bookmarkable_type) {
     
        Element.show('bookmark_spinner');
        new Ajax.Request('/user/add_bookmark',{asynchronous:true, evalScripts:true, onComplete:function(request){
			Element.hide('bookmark_spinner');
			responseText = request.responseText;
			 
			if(responseText == "limit_exceed"){
				update_element_fade('bookmark_status',error_list.limit_exceed);
				return;
			} else if(responseText == "failed") {
				update_element_fade('bookmark_status',error_list.bookmark_add_error);
				return;
			}
			Element.hide('add_bookmark');
			Element.show('remove_bookmark');
        }, parameters:'?bookmarkable_type=' + bookmarkable_type + '&bookmarkable_id='+ bookmarkable_id
	});
	
}

/*This function is used to remove bookmarks to Content, Event, Person, User, and UserSubmittedContent*/
function remove_bookmark(bookmarkable_id, bookmarkable_type) {
        Element.show('bookmark_spinner');
		new Ajax.Request('/user/remove_bookmark',{asynchronous:true, evalScripts:true, onComplete:function(request){
            Element.hide('bookmark_spinner');
			responseText = request.responseText;
			if(responseText == "failed") {
				update_element_fade('bookmark_status',error_list.bookmark_remove_error);
				return;
			}
			Element.hide('remove_bookmark');
			Element.show('add_bookmark');
        }, parameters:'?bookmarkable_type=' + bookmarkable_type + '&bookmarkable_id='+ bookmarkable_id
	});
}

/* This function is used to clear history items */
function clear_history_items(user_id){
	if(confirm_submit(error_list.clear_history_confirmation))
	{
		Element.show('clear_history_items_spinner');
		new Ajax.Request('/user/cb_clear_history',{asynchronous:true, evalScripts:true, onComplete:function(request){
            Element.hide('clear_history_items_spinner');
			$('user_history_count').update('0');
			//responseText = request.responseText;

			/*if(responseText == "failed") {
				update_element_fade('bookmark_status',error_list.bookmark_remove_error);
				return;
			}*/

			/* updating the browser history items */
			oRequestHandlers[0].update("browser_history", "bottom");
        }, parameters:'?user_id=' + user_id
		});
	}
}

/* This function is used to clear switch off browsering history */
function toggle_history(user_id){

	if(confirm_submit(error_list.toggle_history_confirmation))
	{
	    Element.show('toggle_history_spinner');
		new Ajax.Request('/user/cb_toggle_history',{asynchronous:true, evalScripts:true, onComplete:function(request){
            Element.hide('toggle_history_spinner');
			/*
				We want to show profile page without 'History' tab
			*/
			window.location.reload();
			//responseText = request.responseText;
			/*if(responseText == "failed") {
				update_element_fade('bookmark_status',error_list.bookmark_remove_error);
				return;
			}*/
			//in this case we will heve to refresh the whole page as we will not show any history if its enabled
        }, parameters:'?user_id=' + user_id
		});
	}
}

/* This function is used to mark a PM thread as spam */
function msg_mark_spam(thread_id){
	if(confirm_submit("Are you sure you want to mark this message as spam?"))
	{
		new Ajax.Request('/msg_thread/msg_mark_spam',{asynchronous:true, evalScripts:true, onComplete:function(request){
			window.location = location.protocol + "//" + location.host + "/msg_thread/inbox";
        }, parameters:'?thread_id=' + thread_id
		});
	}
}

function commentDelete(comment_id) {
     if(typeof(is_page_completely_loaded) !='undefined') {
         $('q_a_c_id').value = comment_id;
         /*setCookie('q_a_c_id', comment_id);*/
         if(confirm_submit('Are you sure you want to delete this comment?')){
             delete_comment(comment_id);
         }
     }
 }

 function commentEdit(comment_id) {
     moveDivCommentForm('edit_reply_'+comment_id);
    $('postcomment').up().hide();
    $('commentFormMsg').hide();
    $('cancelcomment').up().show();
    $('editcomment').up().show();
    $('comment_id').value = comment_id;
    $('comment_comment').value = $('comm_text_'+comment_id).innerHTML.strip().gsub(/\<br\s?\/?\>/i,"\n").stripTags();
    $('comment_comment').focus();
    return false;
 }

 function commentReply(comment_id) {
     if(typeof(is_page_completely_loaded) !='undefined') {
         //tinyMCE.execCommand('mceRemoveControl', false, 'comment_comment');
		 moveDivCommentForm('edit_reply_'+comment_id);
         //$('comment_comment').value = ''; // remove this for now so that we don't remove a users hard earned comment content
		 $('postcomment').up().show();
         $('cancelcomment').up().show();
         $('editcomment').up().hide();
         $('commentFormMsg').show();
         $('parent_root').value='parent';
         $('comment_parent_id').value = comment_id;
         $('comment_comment').focus();
     }
 }

 function commentPost() {
	 /*
	 try
	 {
		 tinyMCE.execCommand('mceRemoveControl', false, 'comment_comment');
	 }catch(ex)
	 {
		 ex=ex;
	 }
	 */
 	$('postcomment').up().show();
    $('editcomment').up().hide();
	$('comment_comment').value = '';
	$('comment_parent_id').value='';
	//$('comment_content_id').value='';
	$('parent_root').value='root';
	$('editornew').value='new';
	//showContribBox('div_comment_form', 'comment_comment',0, 8);
	showInlineContribBox('div_comment_form', 'comment_comment',0, 8);
	moveDivCommentForm('parent_comment_div');
 }

 function commentReset() {
   remove_previous_error_div();
   moveDivCommentForm("parent_comment_div");
   $('cancelcomment').up().hide();
   $('postcomment').up().show();
   $('editcomment').up().hide();
   $('comment_id').value = '';   
   $('comment_comment').value = '';
   if ($('temp_comment_captcha')) $('temp_comment_captcha').remove();
   //$('comment_comment').value = '';  // remove this for now so that we don't remove a users hard earned comment content
   $('comment_parent_id').value = '';
   $('parent_root').value = '';
   
   var newContent = 'Comments: ' + $$('.comment').size();
   if ($('comments_span')) $('comments_span').update(newContent);
   if ($('commentListCount')) $('commentListCount').update(newContent);
 }

 function hideCommentForms()
 {
	//tinyMCE.execCommand('mceRemoveControl', false, 'comment_comment');
	//tinymce.EditorManager.remove(tinyMCE.get('comment_comment'));
 	if(typeof(is_page_completely_loaded) != 'undefined')
	{
 		var active_div = document.getElementById($('active_comment_div').value);
 		active_div.style.display="none";
 	}
 }

 function moveDivCommentForm(new_parent_id) {
	$('active_comment_div').value = new_parent_id;
 	$(new_parent_id).style.display="";
    var comm_elem = document.getElementById("div_comment_form");
	var newParent = document.getElementById(new_parent_id);

	newParent.appendChild(comm_elem);
    //comm_elem.show();
}

/* This function is used to mark a comment as spam */
function comment_mark_spam(comment_id){
	if(confirm_submit("Are you sure you want to mark this comment as spam?"))
	{
		link_obj = $('flagLink-'+comment_id);
		link_obj.className = (link_obj.className == 'reportAbuse') ? 'reportAbuseWait' : 'reportAbuse';
		new Ajax.Request('/main/comment_mark_spam',{asynchronous:true, evalScripts:true, onComplete:function(request){
			//window.location.reload();
			$('mark-spam-'+comment_id).toggle();
			$('marked-spam-'+comment_id).toggle();
        }, parameters:'?comment_id=' + comment_id
		});
	}
}

/*This funcion is used to resolve spam marked comments by admin*/
function resolve_spam_comment(is_spam, comment_id) {
	if(
        (is_spam=='delete' && confirm_submit("Are you sure you want to delete this comment?")) ||
	   	(!is_spam && confirm_submit("Are you sure you want to mark this comment not as spam?")) ||
		(is_spam && confirm_submit("Are you sure you want to delete this comment permanently?"))
	) {
		new Ajax.Request('/admin/resolve_spam_comment'+'?is_spam='+is_spam+'&comment_id=' + comment_id,
			{
				asynchronous:true, evalScripts:true,
				onComplete:function(request){
					window.location.reload();
				},
				onLoading:function(request) {
					Element.show('div_processing_spinner');
				}
			}
		);
		return false;
	}
}

/*function to change tab for media widget on event/person main page*/
function changeEventMediaTabs(tab1, tab2, tabLbl, tabHref) {
   if($(tab1).className != 'selected') {
	   $(tab2).className = '';
	   $(tab1).className = 'selected';
	   var obj_tab2 = $(tab2 + "_scroll");
	   obj_tab2.style.zIndex = 1;
	   var obj_tab1 = $(tab1 + "_scroll");
	   obj_tab1.style.zIndex = 2;


	   $("mediaTabsLbl").innerHTML = "<a href=\"" + tabHref + "\">" + tabLbl + "</a>";
	   var my_element_collection = obj_tab1.getElementsBySelector('li');
	   if(my_element_collection!=null)
	   {
			var my_child_element = my_element_collection[0].getElementsBySelector('div');
			if(my_child_element != null)
			{
				my_child_element[0].onclick();
			}
	   }

	}
}

function toggleHiddenList(link, list) {
	Element.toggle(list);

	if(link.className == 'left' || link.className == 'leftTemp') {
		link.onmouseout = function() { this.className = (this.className == 'bottomTemp' || this.className == 'bottom') ? 'bottom' : 'left'; }
		link.className = "bottomTemp";
	} else {
		link.onmouseout = function() { this.className = (this.className == 'leftTemp' || this.className == 'left') ? 'left' : 'bottom'; }
		link.className = "leftTemp";
	}
	link.blur();
}

function commentOpens(obj, params_type, params_category, params_filter, params_contributor_filter, requesthandler_type) {
	if(typeof(is_page_completely_loaded)!='undefined') {
		obj.parentNode.className = (obj.parentNode.className =='commentsOpenShow') ? 'commentsOpenHide' : 'commentsOpenShow';
		$('event_comments').toggle();
		if (obj.parentNode.className =='commentsOpenHide' && firstLoad) {
			firstLoad = false;
			Element.toggle('comments_lists_event_landing');
			oRequestHandlers[0].setParameters(params_type, params_category, params_filter, params_contributor_filter);
			requesthandler.type = requesthandler_type;
			oRequestHandlers[0].update('new_comments_landing', 'bottom');
		}
	}
}

function validate_profile_image_upload_form(element_to_check,div_to_add,title,optional_width) {
    var errorhtml = "";

    remove_previous_error_div();

	file_name = $(element_to_check).value.strip();

	if ( file_name == "") {
		errorhtml += "You must select a file.#";
	} else if (!validate_image_file(file_name)) {
		errorhtml += "You must select an image file.#";
	}

    if (errorhtml == "") {
        return true; //in case of successful validation
    } else {
        style = '';
        if (typeof optional_width != "undefined" && optional_width!='') {
            style = optional_width;
        }

        new Insertion.Top(div_to_add,get_error_list_html(errorhtml.split("#"),"error(s) prohibited this " + title.toLowerCase() + " from being saved"));

        return false;
    }
}

function upload_profile_image() {
	var domain = location.protocol + "//" + location.host;
	url = domain + "/user/upload_profile_image";
	getVars = "";

	new Ajax.Request(this.url, {parameters:getVars, asynchronous:true,
			onLoading:function() {
				showDiv('upload_profile_image_spinner');
				hideDiv('upload_profile_image_inner');
			},
			onComplete: function(transport){
				if(transport.responseText=='success') {
					RedBox.close();
					window.location.reload();
				} else {
					showDiv('upload_profile_image_inner');
					hideDiv('upload_profile_image_spinner');
				}
			},
			onFailure: function() {
				showDiv('upload_profile_image_inner');
				hideDiv('upload_profile_image_spinner');
			}
	});
}

function render_comment() {
  try{

   if ($('q_a_c_id').value == null || typeof($('q_a_c_id').value) == "undefined") {
     return false;
   }
   var an_id = $('q_a_c_id').value;
	new Ajax.Request(
        '/main/render_comment/' + an_id,
        {asynchronous:true,
        evalScripts:true,
        onComplete:function(transport){
			$('new_comment_'+an_id).update(transport.responseText);
			$('form_spinner_display').style.display='none';
        },
        parameters:'display_content_detail='+$('display_content_detail').value
        });

  } catch(e)
  {
      log_exceptions("Method :- render_comment " + e.message);
  }
  return false;
};

function get_carrier() {
  try{

	var country = $('country')[$('country').selectedIndex].value;

    if($('country').selectedIndex) {
        $('ajaxWait').show();
        new Ajax.Request(
            '/static/get_carrier/' + escape(country),
            {
                asynchronous:true,
                evalScripts:true,
                onComplete:function(transport){
                    $('carriers').update(transport.responseText);
                    $('carriers').show();
                    $('ajaxWait').hide();
                    $('carrier').disabled = false;
                },
                parameters:''
            }
        );
    }

    // alaways do these steps when switching countries
    $('carrier_number').value = "";
    $('carrier').selectedIndex = 0;
    $('carrier').disabled = true;
    $('cellphone').disabled = true;
    if($('cellphone').value == "") {
         $('cellphone').value = "Your Cellphone"
    }

  } catch(e)
  {
      log_exceptions(" Method :- get_carrier " + e.message);
  }
  return false;
};

function set_carrier_number(){
	var carrier_number = $('carrier')[$('carrier').selectedIndex].value;

    if($('carrier').selectedIndex) {
        $("carrier_number").value = carrier_number;
        $('cellphone').disabled = false;
    } else {
        $("carrier_number").value = "";
        $('cellphone').disabled = true;
        if($('cellphone').value == "") {
            $('cellphone').value = "Your Cellphone";
        }
    }
};

function send_number_via_sms() {
  try{
	var number = $('carrier_number').value;
	var cellphone = $('cellphone').value;

    var msg_went_wrong = "Something went wrong. Did you fill in all fields?";
    var msg_went_right = "You should receive the number on your cellphone in a few seconds!";

    if (number == 'undefined'){
		$('message').update(msg_went_wrong);
	} else if (cellphone == 'undefined' || cellphone=="Your Cellphone"){
		$('message').update(msg_went_wrong);
	} else {
		//$('sendNumber').show();
        $('ajaxWait').show();
        $('carrier').disabled = true;
        $('cellphone').disabled = true;
        $('country').disabled = true;
        $('submitBtn').disabled = true;

        new Ajax.Request(
			'/send_number_to_sms/' + cellphone + '/' + number,
			{
				asynchronous:true,
				evalScripts:true,
				onComplete:function(transport){
					if (transport.responseText=="failed"){
						$('message').update(msg_went_wrong);
                        $('carrier').disabled = false;
                        $('cellphone').disabled = false;
                        $('country').disabled = false;
                        $('submitBtn').disabled = false;
                    }else{
						$('message').update(msg_went_right);
                    }
                    $('ajaxWait').hide();
                },
				parameters:''
			}
		);
	}
  } catch(e)
  {
      log_exceptions(" Method :- send_number_via_sms " + e.message);
  }
  return false;
};

function get_box(whichbox,whichid,finishstr)
{
  str = ($(whichid) ? $(whichid).innerHTML : "");
  /*if (typeof(str) != 'undefined' && str != ''){
	return;
  }*/

  try{
	new Ajax.Request(
		'/static/get_box',
		{
			asynchronous:true,
			evalScripts:true,
			onComplete:function(transport){
				$(whichid).innerHTML = transport.responseText;
		        if (typeof(finishstr) != 'undefined' && finishstr != null) {
		          eval(finishstr);
		        }
				if(whichid=="popupLoginBox"){
					if (FACEBOOK_CONNECT) {
						show_facebook_connect();
					}
				}
				//alert(transport.responseText);
			},
			parameters:'whichbox='+whichbox
		}
	);

  } catch(e)
  {
      log_exceptions(" Method :- get_box " + e.message);
  }
  //return false;
}



//function create_check_facebook_connect_user_callback()
//{
//    try
//    {
//        facebooker_debugger('create_check_facebook_connect_user_callback');
//        var fbu_id = getFBUID();
//        if(fbu_id==null){
//            return;
//        }
//        facebooker_debugger('end create_check_facebook_connect_user_callback');
//        FB.Facebook.apiClient.users_getInfo([fbu_id],["name"],faceboo_user_info);
//        facebooker_debugger('end create_check_facebook_connect_user_callback 22');
//    }catch(ex)
//    {
//        facebooker_debugger("create_check_facebook_connect_user_callback ::" + ex.message);
//    }
//
//}
//function faceboo_user_info(myinfo)
//{
//    try
//    {
//        facebooker_debugger('faceboo_user_info');
//        check_facebook_status(button);
//    }catch(ex)
//    {
//        alert(ex.message);
//    }
//}
//var button=null;
//function create_check_facebook_connect_user(my_button){
//    try{
//        facebooker_debugger('create_check_facebook_connect_user');
//        button = my_button;
//        //alert("button :::" + button);
//        //console.log(button);
//
//        FB.ensureInit(create_check_facebook_connect_user_callback);
//    }catch(ex){
//        alert("create_check_facebook_connect_user :: " + ex.message);
//    }
//}

//function check_facebook_status(button){
//	try {
//        facebooker_debugger('check_facebook_status');
//		new Ajax.Request('/user/check_facebook_status',
//			{
//				asynchronous:false,
//				evalScripts:false,
//   				onComplete:function(transport){
//                    facebooker_debugger('on complete   check_facebook_status');
//					if(transport.responseText=="false"){
//						facebook_prompt_permission('email',
//							function(permission) {
//								if (typeof(permission) != 'undefined' && permission!=false) {
//									createAccountFromFacebookUsingEmail(button);
//								} else {
//									showRegisterBox(button);
//								}
//							}
//						);
//					} else {
//						//logged in
//					}
//				},
//				parameters:"fb_uid=" + getFBUID()
//			}
//		);
//	} catch(e) {
//		alert('Exception in check_facebook_status: ' + e.message);
//	}
//}
/*var permission_callback_facebook = null;
function facebook_promopt_permission_hanlder(result) {
        facebooker_debugger('facebook_prompt_permission') ;
        // prompt offline permission
        if (result == 0)
        {
            // render the permission dialog
            FB.Connect.showPermissionDialog(my_permission, permission_callback_facebook);
        }
        else
        {
            // permission already granted.
            permission_callback_facebook(true);
        }
    }
        */

///*
// * Prompts the user to grant a permission to the application.
// */
//var my_permission = null;
//function facebook_prompt_permission(permission, callbackFunc) {
//    facebooker_debugger('facebook_prompt_permission');
////  ensure_init(function() {
//    //check is user already granted for this permission or not
//    my_permission = permission;
//    permission_callback_facebook = callbackFunc;
//    FB.Facebook.apiClient.users_hasAppPermission(permission,facebook_promopt_permission_hanlder);
////  });
//}

/*function createFacebookAccount(result, button){
    facebooker_debugger('createFacebookAccount');
	try{
		new Ajax.Request('/user/create_user_from_facebook',
			{
				asynchronous:false,
				evalScripts:false,
				onComplete: function(transport){
                    facebooker_debugger('oncomplete of createFacebookAccount`');
					showFacebookConnectBox(button, transport.responseText);
	    		},
				parameters:"fb_username=" + escape(result[0]['name']) + "&fb_email=" + result[0]['proxied_email'] + "&fb_uid=" + getFBUID()
			}
		);
	} catch(e) {
		alert('Exception in createFacebookAccount: ' + e.message);
	}
}

function createAccountFromFacebookUsingEmail(button)
{
	facebooker_debugger('createAccountFromFacebookUsingEmail');
    try
    {
        // show the dialog that we are creating the account
        $('popupFacebookConnectCreateAccount').show();
        FB.Facebook.apiClient.users_getInfo(getFBUID(),['name', 'proxied_email'],create_facebook_account_handler);
    }catch(ex)
    {
        alert('Exception in createAccountFromFacebookUsingEmail');
    }
}*/





/*FB_RequireFeatures(["XFBML"], function()
{
    FB.Facebook.init(window.facebook_api_key, window.facebook_xd_receiver_location);
    //FB.Facebook.init(window.api_key, window.xd_receiver_location);
    FB.Facebook.get_sessionState().waitUntilReady(function() { } );
});*/


/*
 * Ensure Facebook app is initialized and call callback afterward
 */
//function ensure_init(callback) {
//  try{
//        facebooker_debugger('ensure_init');
//        if(!window.facebook_api_key) {
//            window.alert("api_key is not set");
//        }
//        if(window.is_initialized) {
//            callback();
//        } else {
//            /*FB_RequireFeatures(["XFBML", "CanvasUtil"], function() {
//                FB.FBDebug.logLevel = 4;
//                FB.FBDebug.isEnabled = true;
//                FB.Facebook.init(window.facebook_api_key, window.facebook_xd_receiver_location);
//                window.is_initialized = true;
//                callback();
//            });*/
//        }
//    }catch(ex)
//    {
//        alert(ex.message + "ensure_init");
//    }
//}

/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * In a more complex app, this could be used to do some in-page
 * replacements and avoid a full page refresh. For now, just
 * notify the server the user is logged in, and redirect to home.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user, or used
 *                              to create a new account anyway
 */

//function get_session_ready_callback()
//{
//    try
//    {
//        facebooker_debugger('get_session_ready_callback');
//        var user = (FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClient.get_session().uid : null);
//        if (!user)
//        {
//            return;
//        }
//        window.location = window.facebook_authenticate_location;
//    }catch(ex)
//    {
//        alert("get_session_ready_callback ::: " + ex.message);
//    }
//}

//function button_on_click_callback()
//{
//    try{
//        facebooker_debugger('button_on_click_callback');
//        FB.Facebook.get_sessionState().waitUntilReady(get_session_ready_callback);
//    }catch(ex)
//    {
//        alert("button_on_click_callback ::: "  + ex.message);
//    }
//
//}



/* code should be removed after facebook-connect complete */
/*################################################################*/

function set_no_index_flag(event_id) {
  try{
	new Ajax.Request(
		'/main/set_no_index_flag/' + event_id,
		{
			asynchronous:true,
			evalScripts:true,
			onComplete:function(transport){
				if (transport.responseText=="yes") {
					$("hide_crawlers").className = "normal";
                    if($("hide_crawlers").innerHTML == "Hide From Crawlers") {
                        $("hide_crawlers").innerHTML = "Unhide From Crawlers";
                    } else {
                        $("hide_crawlers").innerHTML = "Hide From Crawlers";                         
                    }
                }
			},
			parameters:''
		}
	);

  } catch(e)
  {
      log_exceptions(" Method  :- set_no_index_flag " + e.message);
  }
  return false;
};


function save_blog_url(user_id) {
  try{
	if ($("userBlogUrl").value){
		//if empty
	} else if ($("userBlogUrl").value) {
		// check the format
	} else{
		new Ajax.Request(
			'/main/save_blog_engine/' + user_id,
			{
				asynchronous:true,
				evalScripts:true,
				onComplete:function(transport){
					$("blog_engine_url").hide();
				},
				parameters:'url=' + escape($("userBlogUrl").value)
			}
		);
	}

  } catch(e)
  {
      log_exceptions(" Method :- save_blog_url " + e.message);
  }
  return false;
};

function deleteCredentials(type, str){
  try{
	new Ajax.Request(
		'/delete_credentials/' + type,
		{
			asynchronous:true,
			evalScripts:true,
			onComplete:function(transport){
				if (type=='twitter'){
					$('twitterStatus').innerHTML = transport.responseText;
					$('popupTwitterCompleteBox').hide();
				}
				$(type+'CompleteMessage').innerHTML='Your credentials are now deleted. You can add them back at any time via your profile page.';
				$(type+'CompleteMessage').show();
			},
			parameters:''
		}
	);
  } catch(e)
  {
      log_exceptions(" Method :- deleteCredentials " + e.message);
  }
}
function tweet(link, type, id){

    if(link.className == "twitterLink") {
      try{

        link.className = "twitterLinkWait";

        new Ajax.Request(
            '/tweet/' + type + '/' + id,
            {
                asynchronous:true,
                evalScripts:true,
                onComplete:function(transport){

                    // succesful or not?
                    if(true) {
                        link.className = "twitterLinkLocked"
                        link.innerHTML = "Tweeted"
                        link.title = "Submitted to Twitter"
                        link.onClick = function() { this.blur(); return false; }
                    }

                },
                parameters:''
            }
        );
      } catch(e)
      {
          log_exceptions(" Mehtod :- tweet " + e.message);
      }
    }

    link.blur();
    return false;
}
function is_logged_in() {
	if ($('loggedIn') != null && typeof($('loggedIn')) != "undefined" && $('loggedIn').value > 0) {
		return true;
	} else {
		return false;
	}
}
function toggleAllContacts(checkbox) {

    var checkboxes = null;
    if($('contactsTable'))
    {
        checkboxes = $('contactsTable').getElementsByTagName("INPUT");
    }
    else
    {
        checkboxes = checkbox.parentNode.parentNode.parentNode.getElementsByTagName("INPUT");
    }
    for(var i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].type == "checkbox") {
           checkboxes[i].checked = checkbox.checked;
        }
    }
}

function hasSelectedContact(id, checkbox) {

    var checkboxes = null;
    if($('contactsTable'))
    {
        checkboxes = $('contactsTable').getElementsByTagName("INPUT");
    }
    else
    {
        checkboxes = checkbox.parentNode.parentNode.parentNode.getElementsByTagName("INPUT");
    }
    var return_val = false;
    
    for(var i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].type == "checkbox") {
           if (checkboxes[i].checked) {
           	return_val = true;
           	// this is hack for IE , sets checkbox value to 'on' when doing dom insertion
           	checkboxes[i].value = "" + checkboxes[i].id.split("contact_id" + id + "_")[1];
           }
        }
    }

    return return_val;
}

function showNoContactSelected(id) {
	$('contactsSpinner3'+id).hide();
	$('sendInvitationErrorMessage' + id).innerHTML = 'Please select a contact to invite.';
  $('sendInvitationErrorMessage' + id).show();
}

function send_profile_invitation()
{
    try{
    //validation and message.
    if(!validate_import_contacts())
    {
        $('contactsSpinner3_inline').hide();
        new Insertion.Top($('listContacts_inline'),get_error_list_html(["Please select contacts from the given list"],"error(s) prohibited you from being sending invitations to your friends"));
        return false;
    }

	new Ajax.Request(
        '/user/profile_invite_contacts/',
        {asynchronous:true,
        evalScripts:true,
        onComplete:function(transport){
			try
            {
                var json_data = eval(transport.responseText);
                $('contactsSpinner3_inline').hide();
                if(json_data.status="ok")
                {
                    json_data.error = json_data.error.gsub('#','');
                    $('div_success_message').update('An invitation to join Allvoices has been sent to the following contacts: '+ json_data.error.gsub(',',' '));
                }
                else
                {
                    new Insertion.Top($('listContacts_inline'),get_error_list_html([json_data.error],"error(s) prohibited you from being sending invitations to your friends"));
                }
                window.location.reload();
                return;
            }catch(ex)
            {
                log_exceptions(" Method :- profile_invite_contacts " + ex.message);
            }
        },
        onLoading:function(request){
          //Element.hide('form_table');
          //Element.show('form_spinner_display');
        },
        parameters:$('inviteContact_inline').serialize()
        });

  } catch(e)
  {
      log_exceptions(" Method :-  send_profile_invitation " + e.message);
  }
}

function importContactsForUser(userId, formOptions) {

  new Ajax.Request('/contacts/import', {
    asynchronous: true,
    parameters: $H(formOptions).merge({ userId: userId }),
    onSuccess: function(payload) {
      var itemTemplate = new Template('<li><input type="checkbox" name="contacts[#{id}]" value="1"/><strong>#{name}</strong> (#{email})</li>');
      var listHtml = $A(eval(decode64(payload.responseText))).map(function(contact) {
        return itemTemplate.evaluate(contact);
      }).join("\n");
      $('contacts_list').update(listHtml);
      $('contact_results').show();
    },
    onFailure: function(payload) {
      var responseJSON = eval(decode64(payload.responseText));
      $('error_div').update(responseJSON[0].errorMsg).show();
    },
    onCreate: function() {
      // show spinner
      $('error_div').hide();
      $('status_div').update('Please wait while we import your contacts...').show();
      $('contact_results').hide();
    },
    onComplete: function() {
      // hide spinner
      $('status_div').hide();
    }
  });

}

function resetContactsForm(id) {
	$('importContactsForm'+id).reset();
	$('inviteContact'+id).reset();
	$('contactsSpinner2' + id).style.display = 'none';
	$('skipInvite').value = '';

	var tblObj = $('contactsTable' + id);
    while (tblObj.rows.length>0) //deletes all rows of a table
		tblObj.deleteRow(0) //delete first row of contracting table until there are none left
}

function importContacts(userId, id,refresh_page) {
  if(typeof(refresh_page)=='undefined')
  {
    refresh_page = false;
  }

  var importedEmailsList = $('importedEmails' + id).value;

  /*
  var emailAddr =  $('inviter_email' + id).value + $('inviter_email_provider' + id).value;
  if (importedEmailsList.indexOf(emailAddr) >= 0) {
  	//alert("Already imported contacts for " + emailAddr);
  	$('contactsSpinner' + id).hide();
  	return false;
  }*/

  try{
	new Ajax.Request(
        '/contacts/import/',
        {asynchronous:true,
        evalScripts:true,
        onComplete:function(transport){
			try
            {
                if(refresh_page)
                {
                    window.location.reload();
                    return;
                }

                var json_data = eval(decode64(transport.responseText));
                var tblObj = $('contactsTable' + id);
                var tblBody = tblObj.getElementsByTagName('tbody')[0];

				$('listContactErrorMessage' + id).innerHTML = "";
				$('listContactErrorMessage' + id).hide();
                $('contactsSpinner' + id).hide();

                if (json_data[0].errorMsg != null && json_data[0].errorMsg != "undefined") {
                    $('listContactErrorMessage' + id).innerHTML = json_data[0].errorMsg;
                    $('listContactErrorMessage' + id).style.display = "";
                } else {
                    $('popupInviteContactsBox').show();
                    $('popupInviteContactsBox').style.right = $('popupListContactsBox').style.right;
                    $('popupInviteContactsBox').style.top = $('popupListContactsBox').style.top;
                    $('popupListContactsBox').hide();

                	$('importedEmails' + id).value += "," + $('inviter_email' + id).value + $('inviter_email_provider' + id).value;

                    // set to scroll for contact lists longer than 6
                    if(json_data.length > 6) {
                        $("contactsScroll").className = "contactsWrapper contactsWrapperScroll";
                        setTimeout("var vertScroll = new VertScroll('contactsScroll', 0,0,0, false);",1000);
                    } else {
                        $("contactsScroll").className = "contactsWrapper";
                    }

                    $('inviteContact' + id).show();
                    $('contactsTableHeading' + id).style.display = "";

                    var allChecked = true;

                    for(var i = 0; i < json_data.length; i++ ) {

                        var tr = document.createElement('tr');

                        tr.className = "row" + ((i % 2) ? 0 : 1); // alternating color rows

                        var checkBoxTd = document.createElement("td");
                        var chk = document.createElement('input');

                        chk.setAttribute("id", "contact_id" + id + "_" + json_data[i].id);
                        chk.setAttribute("name", "contact_id["+id+"]");
                        chk.setAttribute("value", json_data[i].id);
                        chk.setAttribute("type", "checkbox");

                        checkBoxTd.appendChild(chk);
                        checkBoxTd.className = "contactsTableCheck"
                        tr.appendChild(checkBoxTd);

                        var nameTd = document.createElement("td");
                        var nameTextNode = document.createTextNode(json_data[i].name);

                        // if name and e-mail are same we only show e-mail
                        if(json_data[i].name != json_data[i].email) {
                            nameTd.appendChild(nameTextNode);
                            nameTd.className = "contactsTableName";
                            tr.appendChild(nameTd);
                        }

                        var emailTd = document.createElement("td");
                        if(json_data[i].name == json_data[i].email) {
                            emailTd.colSpan = "2";
                            emailTd.className = "contactsTableName";
                            // name and email are same, stretch email field
                        } else {
                            emailTd.className = "contactsTableEmail";
                        }

                        var emailTextNode = document.createTextNode(json_data[i].email);
                        emailTd.appendChild(emailTextNode);
                        tr.appendChild(emailTd);

                        tblBody.appendChild(tr);
                        if (json_data[i].has_been_invited == "false")
                        {
                            //chk.setAttribute("checked",true);
                            chk.checked = true;
                        } else {
                            allChecked = false;
                        }

                    }
                    $('contactsCheckAll' + id).checked = allChecked;

                }
            }catch(ex) {
                log_exceptions(" callback of  :-  /contacts/import/ " + ex.message);
            }


        },
        onLoading:function(request){
          //Element.hide('form_table');
          //Element.show('form_spinner_display');
        },
        parameters:'userId=' + userId + '&email=' + encode64($('inviter_email' + id).value + $('inviter_email_provider' + id).value) + '&password=' + encode64($('inviter_password' + id).value)
        });

  } catch(e)
  {
     log_exceptions("Method :- importContacts " + e.message);
  }
  return false;
};

function resetContacts(id) {
	Element.hide('listContactErrorMessage' + id);
	Element.hide('contactsTableHeading' + id);

    var tblObj = $('contactsTable' + id);;
	while (tblObj.rows.length>0) {
		tblObj.deleteRow(0)
	}
};

function postProcessRegistration(userId, id, params) {
  try{

	if (params != 'skip=yes'){
		params = 'userId=' + userId + '&inviterEmail=' + $('hidden_inviter_email' + id).value;
	}
	new Ajax.Request(
        '/post_registration_process',
        {asynchronous:true,
        evalScripts:true,
        onComplete:function(transport){
        },
        onLoading:function(request){
        },
        parameters:params
        });

  } catch(e)
  {
      log_exceptions(" Method :- postProcessRegistration " + e.message);
  }
  return false;
};

function concatenate_contacts(id){
	var c_value = $("concatenatedContacts").value;
    var form = $("inviteContact" + id);
    for (var i=0; i < form.contact_id.length; i++){
	   if (form.contact_id[i].checked){
	      c_value = c_value + form.contact_id[i].value + ",";
	   }
	}

	return c_value;
}

function validEmail(email) {

	if (email == null || email == "") { //check for empty email string
    	return false;
    }

    if (email.indexOf(" ")!=-1){ // no spaces allowed
	    return false
	 }

	var at="@"
	var dot="."
	var indexOfAt = email.indexOf(at)
	var indexOfDot = email.indexOf(dot)

	if (indexOfAt <= 0 || indexOfAt == email.length){ //`@` character cant be the first or last entry
	   return false
	}

	if (indexOfDot <= 0 || indexOfDot == email.length){ //`.` character cant be the first or last entry
	    return false
	}

	 if (email.indexOf(at,(indexOfAt+1)) != -1){ // cant have `@` character in the email domain part
	    return false
	 }

	 if (email.substring(indexOfAt-1, indexOfAt)==dot || email.substring(indexOfAt+1, indexOfAt+2)==dot){ //cant have `.` just before or after the `@`
	    return false
	 }

	 if (email.indexOf(dot,(indexOfAt+2))==-1){ // ensures a `.` atleast 1 character after `@`
	    return false
	 }

	 return true
}

/**/
var user_id = null;
var post_params = "";

/*
 *
 *-This function is used for verification of
 *-Iterate over provided textbox/textarea in questions and return true in case if we give some text in them
 *
 */

function verify_empty_fields(parent_field)
{
    var ret_result = false;
    parent_field = $(parent_field);

    //for fetching all textboxes
    var text_objects = parent_field.getElementsBySelector('[type="text"]');
    var textarea_objects = parent_field.getElementsBySelector('textarea');

    //text inputs
    if(text_objects)
    {
        for(i=0; i<text_objects.length; i++)
        {
            if(text_objects[i].value.strip().length > 0)
            {
                ret_result = true;
                break;
            }
        }
    }

    //textarea objects
    if(textarea_objects && !ret_result)
    {
        for(i=0; i<textarea_objects.length; i++)
        {
            if(textarea_objects[i].value.strip().length > 0)
            {
                ret_result = true;
                break;
            }
        }
    }
    //for fetching all textareas
    return ret_result;
}
function reset_textbox_area(text_objects)
{
    if(text_objects)
    {
        for(i=0;i<text_objects.length;i++)
        {
            text_objects[i].value = '';
        }
    }
}
function reset_radio_buttons(radio_objects)
{
    if(radio_objects)
    {
        for(i=0;i<radio_objects.length;i++)
        {
            radio_objects[i].checked = false;
        }
    }
}
function reset_surevey(reset_type,question_id)
{
    var text_objects = null;
    var textarea_objects = null;
    var raido_objects = null;
    var parent_field = $(question_id);
    if(reset_type == 'text' && parent_field)
    {
        text_objects = parent_field.getElementsBySelector('[type="text"]');
        textarea_objects = parent_field.getElementsBySelector('textarea');

        reset_textbox_area(text_objects);
        reset_textbox_area(textarea_objects);
    }
    else if(reset_type=="radio" && parent_field)
    {
        raido_objects = parent_field.getElementsBySelector('[type="radio"]');
        reset_radio_buttons(raido_objects);
    }
}

function save_post_param()
{
    var errorhtml = "";
    disable_form('form_user_survey',true);
    //disable_buttons('form_user_survey');
    post_params = $('form_user_survey').serialize();
    //verify user selected anyof given buttons or not

    remove_previous_error_div();

	if (!(verifyRadioButton($('form_user_survey').q1) || verify_empty_fields('ul_1')))
	{
    	//verify if any textbox/textarea is not empty. If all empty then give error
        errorhtml += error_list.blank_question_answer + "Question 1.#"
        //errorhtml += "Please select any given option or enter some text in textbox if provided in Question 1.#";
	}

    if (!(verifyRadioButton($('form_user_survey').q2) || verify_empty_fields('ul_2')))
	{
        //verify if any textbox/textarea is not empty. If all empty then give error
        errorhtml += error_list.blank_question_answer + "Question 2.#"
        //errorhtml += "Please select any given option or enter some text in textbox if provided in Question 2.#";
	}
    if (errorhtml == "")
    {
        //return true; //in case of successful validation
        return true;
    } else {
        style = '';
        if (typeof optional_width != "undefined" && optional_width!='') {
            style = optional_width;
        }
        new Insertion.Top('user_survey_error',get_error_list_html(errorhtml.split("#"),"error(s) prohibited this survey from being saved"));
        disable_form('form_user_survey',false);
		return false;
    }

}
// Radio Button Validation
// copyright Stephen Chapman, 15th Nov 2004,14th Sep 2005
// you may copy this function but please keep the copyright notice with it
function verifyRadioButton(radioButtonGroup)
{
    var is_checked_any=false;
    var i=0;
    for(i=0; i<radioButtonGroup.length;i++)
    {
        if(radioButtonGroup[i].checked)
        {
            is_checked_any = true;
        }
    }

    return is_checked_any;
}



function delete_user_account(user_id)
{
    disable_buttons('save_profile_form');
    window.location='/delete/'+user_id;
    return false;
}
function show_survey_box(my_user_id,div_name)
{
    user_id = my_user_id;
    RedBox.showInlineTop(div_name);
}
function post_survey_results(user_id)
{
   var my_user_id = user_id;
   disable_buttons('form_post_survey');
   $('div_spinner_survey').show();
	new Ajax.Request(
            '/survey/post_user_delete_survey/' + my_user_id,
            {
                asynchronous:true,
                evalScripts:true,
                onComplete:function(transport){
                      RedBox.close();
                      delete_user_account(user_id);
                    $('div_spinner_survey').hide();
                    // succesful or not?
                    /*if(true) {
                        link.className = "twitterLinkLocked"
                        link.innerHTML = "Tweeted"
                        link.title = "Submitted to Twitter"
                        link.onClick = function() { this.blur(); return false; }
                    }*/
                },
                parameters:post_params
            }
        );
}

//this method is used to validate passwords on profile page.
function verify_profile_password(div_to_add)
{
    var error_html = "";
    var user_password = ($('user_password') ? $('user_password').value.strip() : "");
    var user_password_confirm = ($('user_password_confirmation') ? $('user_password_confirmation').value.strip() : "");
    if(user_password=="" ||  user_password_confirm=="")
    {
        error_html += error_list.blank_password + "#";
    }

    if(user_password.length < 6 || user_password_confirm.length<6)
    {
        error_html += error_list.min_password_length + "#";
    }

    if(user_password != user_password_confirm)
    {
        error_html += error_list.confirm_password + "#";
    }

    if(error_html == "")
    {
        return true;
    }
    else
    {
        new Insertion.Top($(div_to_add),get_error_list_html(error_html.split("#"),"error(s) prohibited from password being saved"));
        return false;
    }
}

function destroy_recaptcha()
{
    if(typeof('Recaptcha')!='undefined')
    {
        Recaptcha.destroy();
    }
}

function reload_recaptcha()
{
    if(typeof('Recaptcha')!='undefined')
    {
        Recaptcha.reload();
    }
}

function load_recaptcha(change_captcha_id)
{
    //$(change_captcha_id).update('');
    Recaptcha.create(recaptcha_pub_key, change_captcha_id,{theme: "red"});
}

function remove_all_decendants(parent_element)
{
    try
    {
        var lists=$(parent_element).descendants();
        for(i=0;i<lists.length;i++)
        {
            lists[i].remove();
        }
    }catch(ex)
    {
        log_exceptions(" Method :- remove_all_decendants " + ex.message);
    }
}

function create_recaptcha(element_captcha_id)
{
    if(typeof(Recaptcha)!='undefined')
    {
        if($(element_captcha_id).innerHTML.strip()=='')
        {
            Recaptcha.create(recaptcha_pub_key,element_captcha_id,{
                theme: "white"
            });
        }
    }
}

/*  abuse admin related functions   */

 function loadEditor_abuse_admin(is_reporter,user_name,user_id)
  {
      $('form_div').show();
      $('message_progressbar_div').hide();

      RedBox.showInline('compose_message');

      if(is_reporter)
      {
        $('compose_heading').innerHTML='Send PM to Reporter';
      }else
      {
        $('compose_heading').innerHTML='Send PM to Abuser';
      }

      $('recipient_name').innerHTML = user_name;

      $('recipient').value = user_id;

      setTimeout("applyEditor(4,'message_body')",200);

  }

  function send_abuser_reporter_pm()
  {
    try
    {


    if (!confirm_submit('Are you sure you want to send this PM?')){
      return;
    }
    //message_body
    get_tiny_mce_value('message_body');
    var my_params = $('abuser_reporter').serialize();
    //console.log($('abuser_reporter').serialize());
    $('form_div').hide();
    $('message_progressbar_div').show();
    new Ajax.Request('/msg_thread/save/', {
			asynchronous:false,
			evalScripts:true,
			onComplete:function(request){
                          var my_object = eval(request.responseText);
                          $('message_progressbar_div').hide();
                          $('form_div').show();
                          if (my_object && my_object.status=="ok")
                          {
                            alert('message sent successfully');
                            RedBox.close();
                          }
                          else
                          {
                            alert('message sent failed');
                          }

                          //alert(request.responseText);
				//$apro('update_status').update('Event is updated successfully');
				//alert(request.responseText);

                            //return;
			},
			onLoading:function(request){
			   // Element.hide('div_update_event_form'+post_fix);
			   //Element.show('div_update_event_spinner'+post_fix);
                           //alert('onloading function');

			},
			parameters:my_params});
			return true;
            }
            catch(ex)
            {
              log_exceptions("Method :- send_abuser_reporter_pm " + ex.message)
            }
  }
  
function toggleCommentsList(link) {
  $('event_comments').toggle();
  link.up().toggleClassName('commentsOpenHide').toggleClassName('commentsClosedShow');
  return false;
}

function get_syndication_field(i, field_name){
	return "syndication_" + field_name + "_" + i;
}
function updateFields(content_id, field_name, field_ids){
	var field_id_list = field_ids.split(','); // getting all the 
	parent_field = $(get_syndication_field(content_id, field_name));
	
	for(i=0;i<field_id_list.length-1; i++) {
		c_id = field_id_list[i];
		c_object = $(get_syndication_field(c_id, field_name));
		//update the fields
		if(c_id!=content_id && (typeof c_object.value == 'undefined' || c_object.value=='')){
			c_object.value = parent_field.value; 
		}
	}
}

function unlinkPersonForEvent(event_id, people_id) {
  var getVars = "event_id=" + event_id
  getVars += "&people_id=" + people_id
  new Ajax.Request('/unlinkPersonForEvent', 
                  {
                    parameters:getVars,
                    asynchronous:false,
                    onLoading:function() {},
                    onComplete: function(transport) { 
                      $('person_link_'+people_id).hide();
                      $('person_name_'+people_id).show(); 
                    }
                  }
                  );
}

