function ajaxSubmitForm(obj, customprocessfunc, hideErrors) {
    HideErrorsAndSuccessModalBox();
    var serialized = $(obj).serialize();    
    $.ajax({
        type: "POST",
        url: $(obj).attr('action'),
        data: serialized,
        dataType: "json",
        success: function(data) {
            if(typeof(data) == "undefined" || !data || !data.status ||
                data.status == 'error') {
                var errText = '';
                if(data && data.status_text){
                    if(data.status_text) {
                        errText =  data.status_text;
                    }
                } else {
                    errText = 'unknown error status';
                }
                if(!hideErrors) {
                    ErrorModalBox(errText);
                }
                if(customprocessfunc){
                    customprocessfunc(data);
                }                
            } else {
                if(data && data.status_text && !hideErrors) {
                    SuccessModalBox(data.status_text);
                }
                if(customprocessfunc){
                    customprocessfunc(data);
                }
            }

        },

        error: function(XMLHttpRequest, textStatus, errorThrown){
            ErrorModalBox(textStatus);
        }
    });

    // stop the form itself from POSTing
    return false;
}

function ajaxSubmitData(url, data, customprocessfunc, hideErrors) {
    HideErrorsAndSuccessModalBox();
    
    $.ajax({
        type: "POST",
        url: url,
        data: data ? data : null,
        cache: false,
        dataType: "json",
        success: function(data) {
            if(typeof(data) == "undefined" || !data || !data.status ||
                data.status == 'error') {
                var errText = '';
                if(data && data.status_text){
                    if(data.status_text) {
                        errText =  data.status_text;
                    }
                } else {
                    errText = 'unknown error status';
                }
                if(!hideErrors) {
                    ErrorModalBox(errText);
                }
                if(customprocessfunc){
                    customprocessfunc(data);
                }                
            } else {
                if(data && data.status_text && !hideErrors) {
                    SuccessModalBox(data.status_text);
                }
                if(customprocessfunc){
                    customprocessfunc(data);
                }
            }

        },

        error: function(XMLHttpRequest, textStatus, errorThrown){
            ErrorModalBox(url + ': ' + textStatus);
        }
    });

    // stop the form itself from POSTing
    return false;
}

function ajaxLoadHTML(url, HtmlID, sendable, chat, customprocessfunc)
{
    $.ajax({
        url: url + ".html?ajx=2",
        type: sendable ? "POST" : "GET",
        cache: true,
        dataType: "html",
        data: sendable ? sendable: null,
        async: false,
        success: function(data) { 
            if(chat) {
                $('#'+HtmlID).append(data);  
                scrollDown();
            } else {
                $('#'+HtmlID).html(data);  
            }
            
            if(customprocessfunc){
                customprocessfunc(data);
            }
        },  

        error: function(XMLHttpRequest, textStatus, errorThrown){
            ErrorModalBox(url + '.html?ajx=2: ' + textStatus + ': ' + XMLHttpRequest + ': ' + errorThrown);
        }

    });
}

var showNEC = 0;
function CommentSend(obj) {
    var rndval = new Date().getTime();
    if(showNEC == 0) {
        $('#NEC').fadeIn();
        showNEC = 1;
    } else {
        ajaxSubmitForm(obj, function(data) {
            if(data.status == "ok") {
                $('input[name=email]', '.content').val('');
                $('input[name=name]', '.content').val('');
                $('textarea[name=comment]', '.content').val('');
                $('input[name=check_code]', '.content').val('');
                $('#comment-form').remove();
                
                if(data.status_text) {
                    $('#success-sent').fadeIn();
                    $('#success-sent').html(data.status_text);
                }
                
                ajaxLoadHTML(SiteBaseLang + '/comments/refresh/'+data.table+'/'+data.id, 'comment-list');
                
            } else if(data.status == 'error') {
                if(data.errors) {
                    for(i in data.errors) {
                        $('[name='+i+']', '.content').
                        after('<div class="error" id="error-'+i+'">'+data.errors[i]+'</div>');
                    }
                    $('input[name=check_code]').val('');
                }
            }  
            $('#captcha').attr('src', './images/captcha.php?_tm=' + rndval);
        }, true);
        
    }
    
    return false;
}

function SubmitStories(obj) {
    var rndval = new Date().getTime();
    ajaxSubmitForm(obj, function(data) {
            if(data.status == "ok") {
                $('.stories-form').remove();
                
                if(data.status_text) {
                    $('#success-sent').fadeIn();
                    $('#success-sent').html(data.status_text);
                }
                
            } else if(data.status == 'error') {
                if(data.errors) {
                    for(i in data.errors) {
                        $('[name='+i+']', '.content').
                        after('<div class="error" id="error-'+i+'">'+data.errors[i]+'</div>');
                    }
                    
                }
            }  
            $('input[name=check_code]').val('');
            $('#captcha').attr('src', './images/captcha.php?_tm=' + rndval);
        }, true);
        
        return false;
}

function SendMessage(obj) {
    
    ajaxSubmitForm(obj, function(data) {
            if(data.status == "ok") {
                $('input[name=email]', '.content').val('');
                $('input[name=name]', '.content').val('');
                $('textarea[name=text]', '.content').val('');
                
                $('#adv-form').remove();
                
                if(data.status_text) {
                    $('#success-sent').show();
                    $('#success-sent').html(data.status_text);
                }
                
            } else if(data.status == 'error') {
                if(data.errors) {
                    for(i in data.errors) {
                        $('#input-'+i, '#adv-form').
                        after('<div class="error" id="error-'+i+'">'+data.errors[i]+'</div>');
                    }
                    
                }
            }  
        }, true);
    
    return false;
}

function SubmitDelcode(obj) {
    ajaxSubmitForm(obj, function(data) {
            if(data.status == "ok") {
                document.location.href = SiteBaseLang + '/index.html';
                
            } else if(data.status == 'error') {
                if(data.errors) {
                    for(i in data.errors) {
                        $('#input-'+i, '.delpost').
                        after('<div class="error" id="error-'+i+'">'+data.errors[i]+'</div>');
                    }
                    
                }
            }  
        }, true);
        return false;
}

function doStorieVote(voteMarkId, voteStorieId) {
    
    if(voteMarkId && voteStorieId) {
        ajaxSubmitData('stories/rate.html?ajx=1', {id: voteStorieId, mark: voteMarkId}, function(data) {
            if(data.rating) {
                $('.mitem', '.marks').removeClass('active');
                $('[gid='+data.rating+']', '.marks').addClass('active');
                $('.vote', '.rate-block').remove();
            } if(data.myselect) {
                $('[gid='+data.myselect+']', '.marks').addClass('myselect');
            } if(data.sumrate) {
                $('span#s-sumrate').html(data.sumrate);
            }
           
        }, true)
    }
    
    return 1;
}

function ShowVipPreview(obj) {
    return false;
}

function SuccessModalBox(success_text) {
    alert(success_text);
}

function ErrorModalBox(error_text) {
    console.log(error_text);
}

function HideErrorsAndSuccessModalBox() {
    $('div[class=error]').remove();
}

function addBookmark(){
    if (document.all) {
        window.external.AddFavorite(location.href, document.title);
    }
    else if (window.sidebar){
        window.sidebar.addPanel(document.title, location.href, "");
    }
}

function apmvChanged(id)
{
    id_type = document.getElementById('id_type');
    
	if(id == 1) // bezmaksas
	{
		hide_formrow('tr_phone');
		hide_formrow('tr_link');
		hide_formrow('tr_periodpay');
		hide_formrow('tr_code');
		hide_formrow('tr_500code');
		
		show_formrow('tr_periodfree');
		
		if(id_type.value == 11)
		{
		    show_formrow('tr_phone');
		    show_formrow('tr_escortcode'); 
		    hide_formrow('tr_periodfree');  
		    show_formrow('tr_periodescort');         
		}
                $('div[ide=tr_complex]').hide();
	}
	else if(id == 2) // maksas 1.50
	{
		show_formrow('tr_phone');
		hide_formrow('tr_link');
		show_formrow('tr_periodpay');
		
		show_formrow('tr_code');
		
		hide_formrow('tr_periodfree');
		hide_formrow('tr_500code');
		
		if(id_type.value == 11 || id == 1 || id == 9 || id == 12)
		{
		    hide_formrow('tr_escortcode');
		    hide_formrow('tr_periodescort');
		}
                $('div[ide=tr_complex]').hide();
	}
	else if(id == 3)
	{
//	    if(id_type != 11)
//	    {
//	        hide_formrow('tr_phone');
//	    }
            show_formrow('tr_phone');
            hide_formrow('tr_link');
            $('div[ide=tr_complex]').hide();
	}
	else if(id == 4)
	{
	    show_formrow('tr_500code');
	    hide_formrow('tr_escortcode');
	    hide_formrow('tr_code');
	    show_formrow('tr_phone');
	    show_formrow('tr_link');
	    hide_formrow('tr_periodpay');
	    hide_formrow('tr_periodescort');
	    hide_formrow('tr_periodfree');
            
            $('div[ide=tr_complex]').hide();
	} else if(id == 5) {
            show_formrow('tr_phone');
            hide_formrow('tr_link');
            show_formrow('tr_periodpay');

            show_formrow('tr_code');

            hide_formrow('tr_periodfree');
            hide_formrow('tr_500code');

            if(id_type.value == 11 || id == 1 || id == 9 || id == 12)
            {
                hide_formrow('tr_escortcode');
                hide_formrow('tr_periodescort');
            }
            
            $('div[ide=tr_complex]').show();
        } else if(id == 7) {
 
            show_formrow('tr_phone');
        }
}

function typeChanged(id, lang)
{
    if(lang == "lv")
    {
        free = "Bezmaksas";
        pay60 = "Ekonomiskais <b>3.80 EUR</b> - 4.00 (TELE2 ZZ)";
        payGR = "Standarta <b>0.59 EUR</b>";
    }
    else
    {
        free = "Бесплатное";
        pay60 = "Экономичный <b>3.80 EUR</b> - 4.00 (TELE2 ZZ)";
        payGR = "Стандартный <b>0.59 EUR</b>";
    }
    
    radio_text = document.getElementById('apmv_text');
    
    radioAmpV = document.newpost;
    radio_value = getCheckedValue(radioAmpV);
      
	if(id == 12 || id == 11 || id == 1 || id == 9) // escort
	{
            show_formrow('escort_rules');
            show_formrow('escort_rules2');
            show_formrow('card-info-1');
            show_formrow('tr_escortcode');
            show_formrow('tr_periodescort');
            show_formrow('tr_phone');

            hide_formrow('free_rems');
            hide_formrow('tr_periodfree');
            hide_formrow('tr_periodpay');
            hide_formrow('tr_code');
            hide_formrow('tr_500code');
            hide_formrow('nocomerce_rules');
            hide_formrow('econom_apmv');
            radio_text.innerHTML = pay60;
            if(id == 3 || id == 4 || id == 5 || id == 6 || id == 8 || id == 7) {
//                hide_formrow('card-info-1');
//                radio_text.innerHTML = payGR;    
//                show_formrow('free_rems');
//                show_formrow('econom_apmv');
//                hide_formrow('escort_rules2');
               // hide_formrow('tr_phone');
            }
	}
	else
	{
	    hide_formrow('escort_rules');
	    hide_formrow('escort_rules2');
	    hide_formrow('card-info-1');
	    hide_formrow('tr_escortcode');
	    hide_formrow('tr_periodescort');
            hide_formrow('econom_apmv');
	    hide_formrow('tr_periodpay');
	    show_formrow('tr_periodfree');
	    show_formrow('free_rems');
            if(id == 13) {
                show_formrow('nocomerce_rules');
            } else {
                hide_formrow('nocomerce_rules');
            }
	    radio_text.innerHTML = free;
	}
        if((id == 3 || id == 4 || id == 5 || id == 6 || id == 8 || id == 7) && radio_value == 1) {
            hide_formrow('tr_phone');
        }
	if(radio_value == 4)
	{
            hide_formrow('tr_periodfree');
            hide_formrow('tr_periodpay');
            hide_formrow('tr_escortcode');
            show_formrow('tr_500code');
        } else if(radio_value == 7) {
            show_formrow('tr_phone');
        }
}

function show_formrow(row_name)
{
	$('#'+row_name).show();
}

function hide_formrow(row_name)
{
	$('#'+row_name).hide();
}

function hide_objj(obj_name)
{
	$('#'+obj_name).hide();
}

function hide_obj(obj_name)
{
	obj = document.getElementById(obj_name);
	if(obj)
	{
		obj.style.display = "none";
	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setCookie( name, value, domain, expires, path,  secure )
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    if ( expires )  {
         expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    if( !path )
        path = "/" ;

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )	{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}

	if ( !b_cookie_found )	{
		return null;
	}
    
    return true;
}

$(function() {
    $('[data-cookies-alert-button]').click(function() {
       setCookie('isPPAccepted', 1, '.intim24.eu', 365, '/');
       $('[data-cookies-alert]').remove();
    });
});