// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
// namespaces for fitsmi.com
var point_clear=0;
var fitsmi = {
    // Global Javascript Email validation
    valEmail: function(field){
        with (field){
            apos=value.indexOf("@");
            dotpos=value.lastIndexOf(".");
            if (apos<1||dotpos-apos<2){return false;}else{return true;}
        }
    },

    /* chopped email on my account page */
    chopEmail: function (){
        /*
        var str = document.getElementById('my_email').value;
        //var ttt = str.split('@');
        var count=0;
        var chop_str='';
        for(var i=0; i<str.length; i++){
            if(count <= 4){
                chop_str +=str[i];
            }else{
                count=0;
                chop_str +="\n";
            }
            count++;
        }
        document.getElementById('chop_str').innerHTML=chop_str;
        document.getElementById('chop_str').innerHTML=ttt+'<br>';
         */
        var ary = new Array();
        var email = document.getElementById('my_email').value;
        var divId = document.getElementById('chop_email');
        if(email.length >= 25){
            ary = email.split("@");
            for(var i=0;i<ary.length;i++){
                divId.innerHTML = ary[0] + "<br />@" + ary[1];
            }
        }else{
            divId.innerHTML = email;
        }
    },

    togDiv: function (ele) {
        var a = document.getElementById(ele);
        if(a.style.display == "none"){
            a.style.display = "block";
        }else{
            a.style.display = "none";
        }
    },
    toggleBG: function (e, color){e.style.backgroundColor=color;},
    colr1: function (e){e.style.backgroundColor='#EEE';},
    colr2: function (e){e.style.backgroundColor='';},

    popupCenter: function (url, title, pageWidth, pageHeight) {
        var left= (screen.width/2)-(pageWidth/2);
        var top = (screen.height/2)-(pageHeight/2);
        var targetWin = window.open (url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width='+pageWidth+', height='+pageHeight+', top='+top+', left='+left);
    },

    // Ajax popups
    // Please use width:478, height:215 for popup
    // Please use width:395, height: 92 for gray popup
    popupAcceptAsFriend: function () {
        var query_string = "/manage_friends/write_popup_accept_as_friend?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:395, height:92}});
        return false;
    },

     fitsmi_login_error_popup: function() {
        var query_string = "/sessions/popup_login_error?";
        Dialog.info({url:query_string}, {windowParameters: {width:350, height:180}});
        return false;
    },

    popupBlockUser: function (blocked_id) {
        var query_string = "/manage_friends/write_popup_block_user?blocked_user_id= " + blocked_id + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:515, height:310}});
        return false;
    },

    popupUnblockUser: function (blocked_id,status_type) {
        var query_string = "/manage_friends/write_popup_unblock_user?blocked_user_id= " + blocked_id + "&invitation_status=" + status_type + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:478, height:250}});
        return false;
    },

    blocked_user_confirmation: function (blocked_user_name) {
        var query_string = "/manage_friends/write_popup_blocked_user_confirmation?blocked_user_name= " + blocked_user_name + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:478, height:250}});
        return false;
    },

    reality_check_bmi: function (bmi) {
        var query_string = "/changes/write_popup_reality_check_bmi?bmi= " + bmi + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:510, height:310}});
        return false;
    },

    popupRemoveAsFriend: function (friend_id,page_source) {
        var query_string = "/manage_friends/write_popup_remove_as_friend?id=" + friend_id + "&page_source=" +  page_source + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:215}});
        return false;
    },

    add_as_friend_link: function (receiver_id) {
        new Ajax.Request('/manage_friends/show_popupAddAsFriend?receiver_id=' + receiver_id, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    add_to_tracker: function (behaviour_id, behaviour_tracker_id, date, user_id, page_type, filter_by) {
        new Ajax.Request('/manage_account/update_me_page_tracked_changes?behaviour_tracker_id=' + behaviour_tracker_id +'&date=' + date +'&user_id=' + user_id + '&'+behaviour_id+'=true' + '&page_type=' + page_type + '&filter_by=' + filter_by + '&update_done_status=true', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    delete_from_tracker: function (behaviour_tracker_id, date, user_id, page_type, filter_by) {
        new Ajax.Request('/manage_account/update_me_page_tracked_changes?behaviour_tracker_id=' + behaviour_tracker_id +'&date=' + date +'&user_id=' + user_id + '&page_type=' + page_type + '&filter_by=' + filter_by + '&update_done_status=false', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    popupAddAsFriend: function (receiver_id) {
        var query_string = "/manage_friends/write_popup_add_as_friend?id=" + receiver_id + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:250}});
        return false;
    },

    popupAcceptAsFriendConfirmation: function (receiver_id) {
        var query_string = "/manage_friends/write_popup_add_as_friend_confirmation?id=" + receiver_id + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:478, height:215}});
        return false;
    },

    popupAddPhotoComment: function () {
        var query_string = "/photos/write_popup_add_photo_comment?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:395, height:92}});
        return false;
    },

    popupDeletePost: function (user_id,post_id,page_type,wall_type,first_member,second_member,url) {
        if (user_id==null){
            var query_string = "/wall/write_popup_delete_post?post_id=" +  post_id + "&page_type=" + page_type + "&wall_type=" + wall_type + "&first_member=" + first_member + "&second_member=" + second_member +  "&url=" + url + "&authenticity_token=" + window._token;
        }else{
            var query_string = "/wall/write_popup_delete_post?user_id=" + user_id + "&post_id=" +  post_id + "&page_type=" + page_type + "&wall_type=" + wall_type + "&first_member=" + first_member + "&second_member=" + second_member +  "&url=" + url + "&authenticity_token=" + window._token;
        }
        Dialog.info({url:query_string}, {windowParameters: {width:490, height:215}});
        return false;
    },

    popupPostMessageConfirmation: function () {
        var query_string = "/wall/write_popup_post_message_confirmation?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:395, height:92}});
        return false;
    },

    popupPostMessageError: function () {
        var query_string = "/wall/write_popup_post_message_error?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:450, height:92}});
        return false;
    },

    popupMultiplePhotoUploads: function (uploaded_photos) {
        var query_string = "/manage_albums/write_popup_multiple_photo_uploads?uploaded_photos=" + uploaded_photos + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:395, height:92}});
        return false;
    },

    popupRequestAnInvite: function (){
        var query_string = "/sessions/write_popup_request_an_invite?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:510, height:310}});
        return false;
    },

    popupMailToForm: function (){
        var query_string = "/sessions/write_popup_mail_to_form?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:310}});
        return false;
    },

    popupMailToFormConfirmation: function (){
        var query_string = "/sessions/write_popup_helpmail_form_confirmation?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:410}});
        return false;
    },

    popupUploadProfilePhoto: function (user_id) {
        var query_string = "/sessions/write_popup_upload_profile_photo?user_id=" + user_id + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:200}});
        return false;
    },

    check_login_name_availability: function (name){
        new Ajax.Request("/sessions/check_login_name_availability?login_name=" + name , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    popupRemoveApp: function (app_name){
        var query_string = "/manage_account/write_popup_remove_app_from_me_page?app_name=" + app_name + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:200}});
        return false;
    },

    popupRealityCheck: function (user_id){
        var query_string = "/changes/write_popup_reality_check?user_id="+ user_id + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:400}});
        return false;
    },

    popupAddPlanRealityCheck: function (user_id,requested_date){
        var query_string = "/changes/write_popup_reality_check?user_id="+ user_id + "&authenticity_token=" + window._token + "&requested_date=" + requested_date + "&add_plan=true";
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:400}});
        return false;
    },

    popupMePageRealityCheck: function (user_id,requested_date){
        var query_string = "/changes/write_popup_reality_check?user_id="+ user_id + "&authenticity_token=" + window._token + "&requested_date=" + requested_date + "&me_page=true";
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:400}});
        return false;
    },
    
    popupChangesSplash: function (){
        var query_string = "/changes/popup_changes_splash?authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:530, height:'auto'}});
        return false;
    },
    
    popupHelpfulHints: function (){
        var query_string = "/changes/popup_helpful_hints?authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:795, height:'auto'}});
        return false;
    },

    popupEditFrequency: function (behaviour_tracker_id,requested_date){
        var query_string = "/changes/write_popup_edit_frequency?behaviour_tracker_id="+ behaviour_tracker_id + "&requested_date=" + requested_date + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:500}});
        return false;
    },

    popupReplyTopicPost: function (topic_post_id,category){
        var query_string = "/board/write_popup_reply_topic_post?topic_post_id="+ topic_post_id + "&category=" + category + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:500}});
        return false;
    },

    preview_change: function(behaviour_id){
        var query_string = "/admin/write_popup_preview_change?id= " + behaviour_id + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:510, height:310}});
        return false;
    },

    showVid: function(id){
        var element = document.getElementById(id);
        if(element && element.style.visibility== 'hidden') {
            setTimeout(function(){
                element.style.visibility= 'visible';
            }, 1500);
        }
    },
    hideVid: function(id){
        var element = document.getElementById(id);
        if(element){
            element.style.visibility= 'hidden';
        }
    },

    disapper: function () {setTimeout('window.close()',10000);return true;},
    disappear: function (){
        Dialog.cancelCallback();
        fitsmi.showVid('video_container');
        return false;
    },

    /*disapper: function () {setTimeout('window.close()',10000);return true;},
    disappear: function (){Dialog.cancelCallback();return false;},*/

    showDiv: function (e){
        var ele = document.getElementById(e);
        if(ele){ele.style.display = 'block';}
    },
    hideDiv: function (e){document.getElementById(e).style.display='none';},
    hidePointDiv : function (e){new Effect.SlideDownOut(e, {duration: 2, queue: 'end'});},
    showDivs: function (e1, e2){
        document.getElementById(e1).style.display='block';
        document.getElementById(e2).style.display='block';
    },
    hideDivs: function (e1, e2){
        document.getElementById(e1).style.display='none';
        document.getElementById(e2).style.display='none';
    },

    showSelect: function (e1, e2, e3){
        document.getElementById(e1).style.display='block';
        document.getElementById(e2).style.display='block';
        document.getElementById(e3).style.display='none';
    },

    hideSelect: function (e1, e2, e3){
        document.getElementById(e1).style.display='none';
        document.getElementById(e2).style.display='none';
        document.getElementById(e3).style.display='block';
    },

    showElement: function (e1, userid){document.getElementById(e1+userid).style.display='block';},
    hideElement: function (e1, userid){document.getElementById(e1+userid).style.display='none';},

    toggleElement: function(id){
        var ele = document.getElementById(id);
        if(ele.style.display == 'block'){
            ele.style.display = 'none';
        }else{
            ele.style.display = 'block';
        }
    },

    enable_disable_all_chk_boxes: function (total_chk_boxes, check_value){
        for(var i = 0; i <= total_chk_boxes; i++){
            var chk_box = document.getElementById('cb_' + i.toString());
            chk_box.checked = check_value;
        }
    },

    showFriendCategoryForm: function (){ // could we use showDiv() function for this?
        document.getElementById("friend_category_form").style.display='block';
        document.getElementById("add_friend_category_label").style.display='none';
    },

    setFriendCategory: function (user_id, friend_id){
        var friend_category_id = document.getElementById('select_friend_category').value;
        var query_string = "&friend_cat_id=" + friend_category_id + "&user_id=" + user_id + "&friend_id=" + friend_id + "&authenticity_token=" + window._token;
        new Ajax.Request('/manage_friends/set_friend_category', {parameters:query_string, asynchronous:true, history:true, evalScripts:true})
    },

    // Send the Cheers info to rails
    sendCheers: function (receiver_id, cheers_id){
        params_to_pass = "receiver_id=" + receiver_id + "&cheers=" + cheers_id + "&authenticity_token=" + window._token;
        new Ajax.Request('/manage_account/send_cheers', {parameters:params_to_pass, asynchronous:true, history:true, evalScripts:true});return false;
    },
    
    updatesplash: function (user_id){
        params_to_pass = "user_id=" + user_id + "&authenticity_token=" + window._token;
        new Ajax.Request('/manage_account/update_splash', {parameters:params_to_pass, asynchronous:true, history:true, evalScripts:true});
        fitsmi.disappear();
        return false;
    },
    
    showsplash: function(){
        new Ajax.Request('/changes/show_popup_changes_splash', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('75d350c0460faee4e851fc061d809a823c5ca039')});
       var vid = document.getElementById('video_container');
	   if(vid && vid.style.visibility != 'hidden'){
			vid.style.visibility = 'hidden';
		}
        return false;
    },
    
    showhelpfulhints: function(){
        new Ajax.Request('/changes/show_popup_helpful_hints', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent('75d350c0460faee4e851fc061d809a823c5ca039')});
        return false;
    },

    set_app_privacy: function (privacy_status,app_name){
        new Ajax.Request("/manage_account/apps_privacy_setup?app_name=" + app_name + '&privacy_status=' + privacy_status , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    //fitsmi_plan_block_or_unblock: function (value){
        //new Ajax.Request("/admin/fitsmi_plan_block_or_unblock?fitsmi_plan_blocked=" + value , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token}); return false;
    //},

    fitsmi_philosphy_layer_popup: function () {
        var query_string = "/site/write_fitsmi_philosphy_layer_popup?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:945, height:680}});
        return false;
    },

    fitsmi_login_error_popup: function() {
        document.getElementById('video_container').style.visibility= 'hidden';
        var query_string = "/sessions/popup_login_error?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:350, height:180}});
        return false;
    },

    popupChangesLayer: function (){
        var query_string = "/changes/write_popup_changes_layer?&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:905, height:525}});
        return false;
    },

    show_global_app_privacy_popup: function (privacy_status){
        var query_string = "/manage_account/write_popup_global_confirmation?privacy_status=" + privacy_status  + "&authenticity_token=" + window._token;
        Dialog.info({url:query_string}, {windowParameters: {width:500, height:200}});
        return false;
    },

    show_changes_app_count: function (behaviour_id,user_id,report,from_date,to_date){
        new Ajax.Request("/admin/admin_detail_reports?behaviour_id=" + behaviour_id + '&user_id=' + user_id + '&report=' + report + '&from_date=' + from_date + '&to_date=' + to_date  , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    // characters limit
    charTyped: function (element1, element2, charLeft, maxLimit){
        var e1 = document.getElementById(element1);	// a textfield which display the typed characters
        var e2 = document.getElementById(element2);	// a textfield to insert the text
        e1.value = e2.value.split("").length;	// split(" ") - for word count, split("") - for characters count

        if(e2.value.length > maxLimit){
            e2.value = e2.value.substring(0, maxLimit);
        }else{
            charLeft.value = maxLimit - e2.value.length;
        }
        //e1.size = e2.value.length;
        if(e2.value.length >= 10){
            e1.style.width = '15px';
            if(e2.value.length >= 100) {e1.style.width = '22px';}
            if(e2.value.length >= 1000){e1.style.width = '30px';}
        }
        else {e1.style.width = '8px';}
    },

    resetWidth: function (e1, e2){
        var eLeng = document.getElementById(e1).value.length;
        var eWidth= document.getElementById(e2);
        eWidth.value = eLeng;
        if(eLeng >= 10 && eLeng <= 99){
          eWidth.style.width ='15px';
        }else if(eLeng >= 100 && eLeng <= 999){
          eWidth.style.width ='22px';
        }else if(eLeng >= 1000 && eLeng <= 9999){
          eWidth.style.width ='30px';
        }else{
          eWidth.style.width ='8px';
        }
    },

    wall_access_specifier: function (access_group){new Ajax.Request("/access_specifier/wall_access_specifier?access_group_name=" + access_group + '&feature=wall', {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;},
    changemood: function (mood){new Ajax.Request("/manage_account/update_user_mood?mood_name=" + mood , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;},
    selectpoll: function (poll,name){new Ajax.Request("/site/select_poll?poll_id=" + poll+"&poll_name="+name , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;},
    chngImg: function (img_name, img_src){document[img_name].src = "/images/fitsmi_reskinning/"+img_src;},
    redirect_to: function (path){window.location = path;},
    new_win: function (path){window.open = path;},
    borOver: function (e){if(e.value==''){e.style.borderColor = "#f00";}else{e.style.borderColor = "#0f0";}},
    borBlur: function (e){e.style.borderColor = "#bdbdbd";},
    defval: function (ele, val){document.getElementById(ele).value = val;},


    /* Functions for custom checkboxes */
    chked: function (field, image1, image2){
        document.getElementById(image1).style.display = 'none';
        document.getElementById(image2).style.display = 'block';
        document.getElementById(field).checked = true;
    },
    unchk: function (field, image1, image2){
        document.getElementById(image2).style.display = 'none';
        document.getElementById(image1).style.display = 'block';
        document.getElementById(field).checked = false;
    },

    testPassword: function (password){
        var intScore   = 0
        var strVerdict = "weak"
        var strLog     = ""

        // PASSWORD LENGTH
        if (password.length<5){ // length 4 or less
            intScore = (intScore+3)
            strLog   = strLog + "3 points for length (" + password.length + ")\n"
        }else if (password.length>4 && password.length<8){ // length between 5 and 7
            intScore = (intScore+6)
            strLog   = strLog + "6 points for length (" + password.length + ")\n"
        }else if (password.length>7 && password.length<16){ // length between 8 and 15
            intScore = (intScore+12)
            strLog   = strLog + "12 points for length (" + password.length + ")\n"
        }else if (password.length>15){ // length 16 or more
            intScore = (intScore+18)
            strLog   = strLog + "18 point for length (" + password.length + ")\n"
        }

        // LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
        if (password.match(/[a-z]/)){ // [verified] at least one lower case letter
            intScore = (intScore+1)
            strLog   = strLog + "1 point for at least one lower case char\n"
        }
        if (password.match(/[A-Z]/)){ // [verified] at least one upper case letter
            intScore = (intScore+5)
            strLog   = strLog + "5 points for at least one upper case char\n"
        }

        // NUMBERS
        if (password.match(/\d+/)){ // [verified] at least one number
            intScore = (intScore+5)
            strLog   = strLog + "5 points for at least one number\n"
        }

        if (password.match(/(.*[0-9].*[0-9].*[0-9])/)){ // [verified] at least three numbers
            intScore = (intScore+5)
            strLog   = strLog + "5 points for at least three numbers\n"
        }

        // SPECIAL CHAR
        if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)){ // [verified] at least one special character
            intScore = (intScore+5)
            strLog   = strLog + "5 points for at least one special char\n"
        }
        // [verified] at least two special characters
        if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){
            intScore = (intScore+5)
            strLog   = strLog + "5 points for at least two special chars\n"
        }
        // COMBOS
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){ // [verified] both upper and lower case
            intScore = (intScore+2)
            strLog   = strLog + "2 combo points for upper and lower letters\n"
        }
        if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){ // [verified] both letters and numbers
            intScore = (intScore+2)
            strLog   = strLog + "2 combo points for letters and numbers\n"
        }
        // [verified] letters, numbers, and special characters
        if (password.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)){
            intScore = (intScore+2)
            strLog   = strLog + "2 combo points for letters, numbers and special chars\n"
        }

        // checking length of password starts
        if(password.length < 5){
            strVerdict = "too short"
        }else if(intScore < 16){ // checking length of password ends
            strVerdict = "very weak"
        }else if (intScore > 15 && intScore < 25){
            strVerdict = "weak"
        }else if (intScore > 24 && intScore < 35){
            strVerdict = "good"
        }else if (intScore > 34 && intScore < 45){
            strVerdict = "strong";
        }else{
            strVerdict = "stronger";
        }

        /* document.forms.passwordForm.score.value = (intScore)
         document.forms.passwordForm.verdict.value = (strVerdict)
        document.forms.passwordForm.matchlog.value = (strLog)*/
        document.forms.passwordForm.verdict.value = (strVerdict)
        document.getElementById('testing').value = strVerdict
    },

    markEatChangeCount: function (element,max_count) {
        var element_id_array=element.split("_");
        var first_part = element_id_array[0]
        var second_part = element_id_array[1]
        var third_part = element_id_array[2]
        var integer_count = parseInt(second_part);
        if(third_part == "empty") {
            for(var a=1; a <= integer_count; a++){
                var target_visible_element = [first_part,a,'filled'].join('_')
                var target_hidden_element = [first_part,a,'empty'].join('_')
                var target_count_element = [first_part,'count'].join('_')
                document.getElementById(target_visible_element).style.display = "block";
                document.getElementById(target_hidden_element).style.display = "none";
                document.getElementById(target_count_element).value = integer_count;
            }
        } else {
            if(integer_count == max_count || integer_count == 1){
                for(var a=integer_count; a <= max_count; a++){
                    var target_hidden_element = [first_part,a,'filled'].join('_')
                    var target_visible_element = [first_part,a,'empty'].join('_')
                    var target_count_element = [first_part,'count'].join('_')
                    document.getElementById(target_visible_element).style.display = "block";
                    document.getElementById(target_hidden_element).style.display = "none";
                    document.getElementById(target_count_element).value = integer_count-1;
                }
            } else {
                for(var a=integer_count+1; a <= max_count; a++){
                    var target_hidden_element = [first_part,a,'filled'].join('_')
                    var target_visible_element = [first_part,a,'empty'].join('_')
                    var target_count_element = [first_part,'count'].join('_')
                    document.getElementById(target_visible_element).style.display = "block";
                    document.getElementById(target_hidden_element).style.display = "none";
                    document.getElementById(target_count_element).value = integer_count;
                }
            }
        }
    },

    setEatChangeBoxes: function (element,count){
        //alert(count);
        for(var a=1; a <= count; a++){
            var target_visible_element = [element,a,'filled'].join('_')
            var target_hidden_element = [element,a,'empty'].join('_')
            document.getElementById(target_visible_element).style.display = "block";
            document.getElementById(target_hidden_element).style.display = "none";
        }
    },

    checkPlanEatChangeDoneStatus: function (element1,element2,element3,element4,element5,element6,element7){
        if(document.getElementById(element1).style.display == "block" && document.getElementById(element2).style.display == "block" && document.getElementById(element3).style.display == "block" && document.getElementById(element4).style.display == "block" && document.getElementById(element5).style.display == "block" && document.getElementById(element6).style.display == "block" && document.getElementById(element7).style.display == "block"){
            document.getElementById('plan_check_c1').style.display = 'none';
            document.getElementById('plan_check_c2').style.display = 'block';
        } else {
            document.getElementById('plan_check_c2').style.display = 'none';
            document.getElementById('plan_check_c1').style.display = 'block';
        }
    },

    changetext: function (text_a,text_b){
//        if(window.sample) window.document["sample"].SetVariable("text1", text_a);
//        if(document.sample) document.sample.SetVariable("text1",  text_a);
//
//        if(window.sample) window.document["sample"].SetVariable("text2", text_b);
//        if(document.sample) document.sample.SetVariable("text2", text_b);
//
//        if(window.sample) window.document["sample"].Play();
//        if(document.sample) document.sample.Play();
            //hidePointDiv('flex_notification');
            clearTimeout(point_clear);
            document.getElementById('flex_notification').style.display = 'block';
            document.getElementById('point_desc_id').innerHTML = "<h3>" + text_a + " points </h3>" + "<br/>" + '<p>' + text_b + '</p>';
            point_clear=setTimeout("fitsmi.hidePointDiv('flex_notification')",5000);
            new Effect.SlideUpIn('point_desc_id', {duration: 2, queue: 'end'});

    },

    show_add_to_tracker_popup: function (element){
            var element_id_array=element.split("n");
            var first_part = element_id_array[0]
            var second_part = element_id_array[1]
            for(var a=0; a < 5; a++){
                var target_element = [first_part,a].join('n');
                if(document.getElementById(target_element).style.display == 'block'){
                    document.getElementById(target_element).style.display = 'none';
                }

                document.getElementById(element).style.display = 'block';
            }
    },

    /* revert z-index for quote images */
    revertIndex: function (){
        var clip = document.getElementById('clip_container');
        if(clip.style.zIndex == 1979){
            clip.style.zIndex = 1;
        }else{
            clip.style.zIndex = 1979
        }
    },

    addMoveMinutes: function (options,prefix,parentElem){
        var element_id_array = options.split('$');
        var first_part = element_id_array[0];
        var second_part = element_id_array[1];
        var string = document.getElementById(first_part).value + " minutes of " + document.getElementById(second_part).value;

        var divElem = document.createElement("div");
        var inputElem = document.createElement("input");
        inputElem.type = "text";
        inputElem.value = string;
        inputElem.size = inputElem.value.length;
        inputElem.style.display = 'block';
        inputElem.style.marginBottom = '5px';
        inputElem.style.borderStyle = 'none';
        inputElem.readOnly = true;

        for(var a=1; a < 9; a++){
            element=document.getElementById(prefix + a + '_div');
            if(element){}
            else {
                var suffix = a;
                break;
            }
        }

        inputElem.id = prefix + suffix;
        inputElem.name = prefix + suffix;
        var inputDiv = document.createElement('div');
        var closeButtonDiv = document.createElement('div');

        divElem.id = inputElem.id + '_div';
        divElem.style.clear = 'both';
        divElem.style.width = '650px';

        inputDiv.id = inputElem.id + '_inputdiv';
        inputDiv.style.cssFloat = 'left';
        inputDiv.style.width = inputElem.size;

        closeButtonDiv.id = inputElem.id + '_closediv';
        closeButtonDiv.style.cssFloat = 'left';
        closeButtonDiv.style.width = '25px';

        document.getElementById(parentElem).appendChild(divElem);
        document.getElementById(divElem.id).appendChild(inputDiv);
        document.getElementById(inputDiv.id).appendChild(inputElem);
        document.getElementById(divElem.id).appendChild(closeButtonDiv);
        closeButtonDiv.innerHTML = ' | <a class="hand" onClick="fitsmi.removeMoveMinutes(\'' + inputElem.id + '\');">x</a>';
    },

    removeMoveMinutes: function (inputElemId){
        inputElem = document.getElementById(inputElemId);
        inputElem.value = "";
        var divElem = inputElemId + '_div';
        document.getElementById(divElem).style.display = 'none';
    },

    //this function made for CMS page tab(eat,move,inspire,style)
    send_params: function (user_id,user_points,sc_id,locat, target){
        //window.parent.location.href = locat, target;
        document.myform.action=locat;
        window.parent.location.href = locat, target;
        document.myform.user_id.value=user_id;document.myform.submit();return false
        document.myform.user_points.value=user_points;document.myform.submit();return false
        document.myform.sc_id.value=sc_id;
        document.myform.submit();
        return false
    },

    /* showing confirmation when user tries to add the exercise */
    check_added_exercise: function (exercise_id){
        var selected_exercise_name = document.getElementById(exercise_id).value ;
        var i;
        var exercise_name;
        for(i=1; i<9; i++){
            var exercise_div = document.getElementById("move_behaviour_7_" + i);
            if (exercise_div){
                exercise_name=exercise_div.innerHTML;
                if (exercise_name.match(selected_exercise_name)){
                    var r=confirm("You've added the same exercise twice. Did you mean to do that?");
                    if (r==false){
                        return false;
                    }
                    break;
                }
            } else {
                break;
            }
        }
    },

    /* showing confirmation when user tries to add the exercise from plan */
    check_plan_added_exercise: function (exercise_id){
        var selected_exercise_name = document.getElementById(exercise_id).value ;
        var i;
        var exercise_name;
        for(i=1; i<9; i++){
            var exercise_div = document.getElementById("plan_move_behaviour_7_" + i);
            if (exercise_div){
                exercise_name=exercise_div.innerHTML;
                if (exercise_name.match(selected_exercise_name)){
                    var r=confirm("You've added the same exercise twice. Did you mean to do that?");
                    if (r==false){
                        return false;
                    }
                    break;
                }
            } else {
                break;
            }
        }
    },

    /* request brochure validation */
    chkRequestBrochure: function () {
      with(document.brochure){
        var err = document.getElementById('error_msg');
        if(username.value==''){err.innerHTML='Please type your name';username.focus();return false;}
        if(degree.value==''){err.innerHTML='Please type your degree';degree.focus();return false;}
        if(practice_type.value==''){err.innerHTML='Please type practice_type';practice_type.focus();return false;}
        if(mail_from.value==''){err.innerHTML='Please type your mail_from';mail_from.focus();return false;}
        if(city.value==''){err.innerHTML='Please type your city';city.focus();return false;}
        if(state.value==''){err.innerHTML='Please type your state';state.focus();return false;}
        if(email.value==''){err.innerHTML='Please type your email';email.focus();return false;}
        if(email.value.indexOf(" ") > -1){err.innerHTML = "Do not leave spaces in Email field!";email.focus();return false;}
        if(valEmail(email)==false){err.innerHTML = "Invalid Email ID!";email.focus();return false;}
        if(phone.value==''){err.innerHTML='Please type your phone';phone.focus();return false;}
        if(quantity.value==''){err.innerHTML='Please type quantity';quantity.focus();return false;}
        return true;
      }
    },

    show_chained_change_type: function (ui_change_type,counter){
        new Ajax.Request("/admin/show_chained_html_types_list?ui_change_type=" + ui_change_type +"&counter=" + counter , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    show_change_type: function (ui_change_type){
        new Ajax.Request("/admin/show_html_types_list?ui_change_type=" + ui_change_type , {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + window._token});return false;
    },

    focusfields: function(){
        var search_field = document.getElementById('site_search_field');
        var login_field = document.getElementById('login');
        var pass_field = document.getElementById('password');

        if(search_field){
            search_field.onfocus = function(){if(this.value=='Search'){this.value='';}}
            search_field.onblur = function(){if(this.value==''){this.value='Search';}}
        }
        if(login_field && pass_field){
            login_field.onfocus = function(){if(this.value=='Email'){this.value='';}}
            login_field.onblur = function(){if(this.value==''){this.value='Email';}}
            pass_field.onfocus = function(){if(this.value=='Password'){this.value='';}}
            pass_field.onblur = function(){if(this.value==''){this.value='Password';}}
        }
    },
    
    auto_height_iframe: function(iframe_id){
        var ifid =document.getElementById(iframe_id);
        if(ifid){
          //if(navigator.appName == 'Microsoft Internet Explorer'){
            ifid.style.height = ifid.contentWindow.document.body.scrollHeight + 'px';
          //}else{
           //ifid.style.height = '100%';
         // }
        }
    },
    
    wp_static_iframe_height: function(){ // for privacy, terms, help, about, clinician etc. pages
        var wpsf_id =document.getElementById('wp_static_iframe');
        if(wpsf_id){
          if(navigator.appName == 'Microsoft Internet Explorer'){
            wpsf_id.style.height = wpsf_id.contentWindow.document.body.scrollHeight + 'px';
          }else{
            wpsf_id.style.height = '100%';
          }
        }
    }

}

function check_blank_fields(){

          var url = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
          //url.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
          if(document.getElementById("title").value==''){
              alert("Section Title cannot be blank");
              return false;
          }

          if(document.getElementById("title_0").value==''){
              alert("Content Title1 cannot be blank");
              return false;
          }

          var url_0 = document.getElementById("url_0").value;
          if (!url.test(url_0)){
              alert("Please enter a valid url for Content Title1. Example: http://www.sitename.com");
              return false;
          }

          if(document.getElementById("title_1").value==''){
              alert("Content Title2 cannot be blank");
              return false;
          }

          var url_1 = document.getElementById("url_1").value;
          if (!url.test(url_1)){
              alert("Please enter a valid url for Content Title2. Example: http://www.sitename.com");
              return false;
          }

          if(document.getElementById("title_2").value==''){
              alert("Content Title 3 cannot be blank");
              return false;
          }

          var url_2 = document.getElementById("url_2").value;
          if (!url.test(url_2)){
              alert("Please enter a valid url for Content Title3. Example: http://www.sitename.com");
              return false;
          }

          var url_3 = document.getElementById("url_3").value;
          if(document.getElementById("title_3").value!=''){
              if (!url.test(url_3)){
                alert("Please enter a valid url for Content Title4. Example: http://www.sitename.com");
                return false;
              }
          }


          if (url.test(url_3)){
              if(document.getElementById("title_3").value==''){
                alert("Content Title 4 cannot be blank");
                return false;
              }
          }

          var url_4 = document.getElementById("url_4").value;
          if(document.getElementById("title_4").value!=''){
              if (!url.test(url_4)){
                alert("Please enter a valid url for Content Title5. Example: http://www.sitename.com");
                return false;
              }
          }

}
