var currentServiceId = 0;
var currentCategory = 'law';
var accountsEnable = false;
var scriptEnable = false;
var accountsMax;
var accountsMin;

var isCatalogs = false;

var price;

var waitBox;

$(document).ready(function(){
    
    var serviceOrderFormOptions = {
        beforeSubmit:  serviceOrderRequest,
        success:       serviceOrderResponse
    } 
      
    $('#serviceOrderForm').submit(function() { 
        
        if(scriptEnable)
	    {
	        if(currentCategory == '')
	        {
	            MessageBox(Chiptop.TXT_SELECT_CATEGORY);
	            return false;
	        }      
	        siteUrl = $('input#url').val();
	        var regexp = /http:\/\/([\w-.]+)(\/.*)?/;
	        var matches = siteUrl.match(regexp);
	        if(matches && matches[1])
	        {
	           $('#reg_link').val("http://"+matches[1]+"/category/"+currentCategory+"/%host_reg%.php");
	           if(waitBox)
			    {
			        waitBox.show();
			    }
			    else
			    {
			        waitBox = new Boxy($('#waitBox'), {closeable: false});
			    }   
	           $.post(Chiptop.URL_CHECK_SCRIPT, { domain: matches[1], category: currentCategory }, function(data){
	                waitBox.hide();
	                eval("var response = "+data+";");
	                if(response.error == "0")
                    {
		                if(response.data.result != "ok")
	                    {
	                        MessageBox(Chiptop.TXT_ERR_WRONG_SCRIPT_CRC);
	                        $('a.download_script').each(function(){$(this).attr('href', 'http://cheaptop.ru/allsub/category_'+currentCategory+'.zip');});
	                        return false;                        
	                    }                         
	                    $('#serviceOrderForm').ajaxSubmit(serviceOrderFormOptions);
                    }
                    else
                    {
                        MessageBox(response.message);
                        $('a.download_script').each(function(){$(this).attr('href', 'http://cheaptop.ru/allsub/category_'+currentCategory+'.zip');});
                        return false;
                    }
	           });
	        }
	        else
	        {
	           MessageBox(Chiptop.TXT_INVALID_URL);
	           return false;
	        }
	    }
        else
        {
            $('#serviceOrderForm').ajaxSubmit(serviceOrderFormOptions);
        } 
        return false; 
    }); 
    
    $('.linkOrderService').click(function(){
        $('td.boxy-inner div.title-bar a.close').each(function(){ $(this).click(); });
		currentServiceId = $(this).attr("id").replace(/linkOrderService_/, "");
		
        $.get(Chiptop.URL_CHECK_AUTH, function(data){
            if(data == "0") {
                document.location.href = Chiptop.URL_AUTH_FOR_ORDER;
            }
            else
            {
            	$.post(Chiptop.URL_CHECK_CREDIT_TO_ORDER, { service: currentServiceId }, function(data){
				    eval("var response = "+data+";"); 
				    if(response.error == "0")
    				{       	
				        $('#serviceOrderBox .boxSuccessMessage').hide();
				        $('#serviceOrderBox .boxErrorMessage').hide();
				        $('#serviceOrderForm').resetForm();
				        $('#serviceOrderBox .papers_block').each(function(){ $(this).hide(); });
				        $('#serviceOrderBox #keywords_block .grid_title').html(Chiptop.TXT_KEYWORDS);
                        $('#serviceOrderBox #keywords_block .example').html(Chiptop.TXT_EXAMPLE_KEYWORDS);
				        hideScriptInfo();
				        
				        price = parseFloat($('#priceService_'+currentServiceId+" .price").text().replace("$", ""));
				        var total = price + projPrice;                          
                $('#total').html("$"+total+" (+$"+projPrice+" "+Chiptop.TXT_PROJECT+")");
				        
				        
				        $('#serviceOrderBox h3').html($('#titleService_'+currentServiceId).text()+" &mdash; "+$('#priceService_'+currentServiceId).text());
				        $('#service_id').val(currentServiceId);
				                
				        if(response.data.accounts_enable == "1")
				        {
				            accountsEnable = true;
				            accountsMax = parseInt(response.data.accounts_max);
				            accountsMin = parseInt(response.data.accounts_min);
				            $('#accounts_max').html(accountsMax);
				            $('#accounts_min').val(accountsMin);
				            $('#serviceOrderBox tr.accounts').removeClass('hidden');				            
				            $('#accounts_min').change(function(){
				                if(parseInt($(this).val())-accountsMin >= 0)
				                {
					                var total = price + projPrice + (parseFloat(parseInt($(this).val())-accountsMin) * parseFloat(response.data.accounts_price));
					                $('#total').html("$"+total+" (+$"+projPrice+" "+Chiptop.TXT_PROJECT+")");
					                if(skipProjDialog)
                                    {
                                        $('#total').html("$"+total);
                                    }
					            } else { 
					               MessageBox(Chiptop.TXT_ERR_WRONG_ACCOUNT_MIN_AMOUNT + ": " + accountsMin);
					               $(this).val(accountsMin); 
					               $(this).change();
					            }
				            });	
				            $('#accounts_min').change();				            
				        }
				        else
				        {
				            $('#serviceOrderBox tr.accounts').addClass('hidden');
                            accountsEnable = false;
				        }
				        
				        if(response.data.script == "1")
                        {
                            $('#serviceOrderBox tr.script_info').each(function(){ $(this).removeClass('hidden'); }); 
                            $('#serviceOrderBox tr.total').removeClass('hidden');
                            isCatalogs = true;          
				        }
				        else
				        {
				        	$('#serviceOrderBox tr.script_info').each(function(){ $(this).addClass('hidden'); }); 
				        }
				        
				        if(skipProjDialog)
				        {
				            $('#serviceOrderBox tr.accounts td.grid_title').html(Chiptop.TXT_COMMENTS_AMOUNT);
				            $('#serviceOrderBox #keywords_block').hide();
				            $('#serviceOrderBox #accountsMaxWarning').remove();				            
				            $('#total').html("$"+total);				            
				            if(!orderBox)
				            {
				                orderBox = new Boxy($('#serviceOrderBox'), {title: $('#serviceGroupTitle').text()});
				            }
				            else
				            {
				                orderBox.show();
				            }                         
				            alignToCenterDialogs();
				        }
				        else if (in_array(currentServiceId, skipProjDialogTariffId)) {
				            $('#serviceOrderBox tr.accounts td.grid_title').html(Chiptop.TXT_COMMENTS_AMOUNT);
				            $('#serviceOrderBox #keywords_block').hide();
				            $('#serviceOrderBox #accountsMaxWarning').remove();				            
				            $('#total').html("$"+price);				            
				            if(!orderBox)
				            {
				                orderBox = new Boxy($('#serviceOrderBox'), {title: $('#serviceGroupTitle').text()});
				            }
				            else
				            {
				                orderBox.show();
				            }                         
				            alignToCenterDialogs();				        
				        }
				        else if (in_array(currentServiceId, papersTariffId))
				        {
				        	$('#serviceOrderBox #keywords_block .grid_title').html(Chiptop.TXT_PAPER_TOPIC);
				        	$('#serviceOrderBox #keywords_block .example').html(Chiptop.TXT_PAPER_TOPIC_RECOMMENDATIONS);
                            $('#serviceOrderBox .papers_block').each(function(){ $(this).show(); });                   
                            $('#total').html("$"+price);                            
                            if(!orderBox)
                            {
                                orderBox = new Boxy($('#serviceOrderBox'), {title: $('#serviceGroupTitle').text()});
                            }
                            else
                            {
                                orderBox.show();
                            }                         
                            alignToCenterDialogs();
				        }
				        else
				        {		    		        
					        $("#projectBox #order .bold").html('+$'+projPrice); 
	                        if(projectBox)
	                        {
	                            projectBox.show();
	                        }
	                        else
	                        {
	                            projectBox = new Boxy($('#projectBox'), {title: $('#serviceGroupTitle').text()});
	                            alignToCenterDialogs();	                            
	                        }
	                    }
    				}
    				else
    				{
    					MessageBox(response.message);    					
    				}
				});
            }            
        });
    });
    
    $('table#category td').click(function(){
        $('table#category td.darkGreen').removeClass('darkGreen').removeClass('bold');
        $(this).addClass('darkGreen').addClass('bold');
        currentCategory = $(this).attr('id');             
    });
    
    $('a#instruction').click(function(){
        MessageBox(Chiptop.TXT_INSTALL_SCRIPT_INSTRUCTION);
    });
    
    $('a.script_description').click(function(){
        MessageBox(Chiptop.TXT_INSTALL_SCRIPT_INSTRUCTION_FULL);
    });
    
    $('input#install_script').click(function(){
        if(elem('install_script').checked)
        {
            showScriptInfo();
        }
        else
        {
            hideScriptInfo();
        }                                
    });
    
    $('#serviceOrderBox input#order_template').click(function(){
        if(elem('order_template').checked)
        {
            var total = price + 2 + projPrice;
            $('#total').html("$"+total+" (+$"+projPrice+" "+Chiptop.TXT_PROJECT+")");
				    var currentServiceId = $('#service_id').val();
				    if (in_array(currentServiceId, skipProjDialogTariffId)) {		          
							$('#total').html("$"+price);	
						}    
            //$('#total').html("$"+total);
        }
        else
        {
            var total = price + projPrice;
            $('#total').html("$"+total+" (+$"+projPrice+" "+Chiptop.TXT_PROJECT+")");
				    var currentServiceId = $('#service_id').val();
				    if (in_array(currentServiceId, skipProjDialogTariffId)) {		          
							$('#total').html("$"+price);	
						}    
            //$('#total').html("$"+total);
        }                                
    });
    
    $("#projectBox .item").click(function(){
        projectBox.hide();
        var id = $(this).attr("id");
        if(id == "order")
        {
            if(!orderBox)
            {
                orderBox = new Boxy($('#serviceOrderBox'), {title: $('#serviceGroupTitle').text()});
            }
            else
            {
                orderBox.show();
            }                         
	        alignToCenterDialogs();
        }
        if(id == "youself")
        {
            if(isCatalogs)
            {
                toUrl(Chiptop.URL_ORDER_CATALOG + currentServiceId);
            }
            else
            {
                toUrl(Chiptop.URL_ORDER_SOCIAL + currentServiceId);
            }                        
        }
    });
    
    $("#projectBox .item").mouseover(function(){
        $(this).addClass('over');
    });
    
    $("#projectBox .item").mouseout(function(){
        $(this).removeClass('over');
    });
    
    
});

function showScriptInfo() {
    scriptEnable = true;
    $('#serviceOrderBox tr.script_area').each(function(){ $(this).removeClass('hidden'); }); 
    elem('order_template').checked = true;
    var total = price + 2 + projPrice;
    $('#total').html("$"+total+" (+$"+projPrice+" "+Chiptop.TXT_PROJECT+")");
    var currentServiceId = $('#service_id').val();
    if (in_array(currentServiceId, skipProjDialogTariffId)) {		          
    	$('#serviceOrderBox label[for=order_template]').html('Закажите формирование шаблона');
			$('#total').html("$"+price);	
		} else {
			$('#serviceOrderBox label[for=order_template]').html('Закажите формирование шаблона (+$2)');
		}
		$('#serviceOrderBox tr.script_area:has(#category)').hide();
    alignToCenterDialogs();
}

function hideScriptInfo() {
    scriptEnable = false;
    $('#serviceOrderBox tr.script_area').each(function(){ $(this).addClass('hidden'); }); 
    $('table#category td.darkGreen').removeClass('darkGreen').removeClass('bold');
    currentCategory = 'law';
    elem('order_template').checked = false;
    var total = price + projPrice;
    $('#total').html("$"+total+" (+$"+projPrice+" "+Chiptop.TXT_PROJECT+")");
    var currentServiceId = $('#service_id').val();
    if (in_array(currentServiceId, skipProjDialogTariffId)) {		          
			$('#total').html("$"+price);	
		}    
    alignToCenterDialogs();
}


/* Events Listeners */

function serviceOrderRequest(formData, jqForm, options) {     
    $('#serviceOrderBox .boxSuccessMessage').hide();
    data = formDataToArray(formData);    
    if(data.url == "" || data.email == "") {
        MessageBox(Chiptop.TXT_SOME_REQUIRED_FIELDS_IS_EMPTY);                
        return false;    
    }
	if(accountsEnable)
	{
	    if(parseInt(data.accounts) >= accountsMin)
	    {
		    if(accountsMax < parseInt(data.accounts)) {
		        MessageBox($('#accountsMaxWarning').text());
		        return false;
		    }
	    }
	    else
	    {
	        MessageBox(Chiptop.TXT_ERR_WRONG_ACCOUNT_MIN_AMOUNT + ": " + accountsMin);
	        $('#accounts_min').val(accountsMin);
	        return false;
	    }
	}
	
    $('#serviceOrderBox .boxErrorMessage').hide(); 
    if(waitBox)
    {
        waitBox.show();
    }
    else
    {
        waitBox = new Boxy($('#waitBox'), {closeable: false});
    }   
    return true;
}

function serviceOrderResponse(responseText, statusText)  { 
    //$('#serviceOrderBox .boxWaitMessage').hide();
    waitBox.hide();
    eval("var response = "+responseText+";");
    if(response.error == "0")
    {
        //$('#serviceOrderBox .boxSuccessMessage').html(response.message).show();
        $('#credit').html(response.data.credit);
        $('#bonus').html(response.data.bonus);
        $('#creditTable').addClass('yellow_background');
        window.setTimeout(function(){
            $('#creditTable').removeClass('yellow_background');
        },2000);            
        $('#serviceOrderForm').resetForm();
        $('#service_id').val(currentServiceId);
        $('td.boxy-inner div.title-bar a.close').each(function(){ $(this).click(); });
        MessageBox(response.message);
    }
    else
    {
        MessageBox(response.message);
    }
}
