var webRoot,langCode,randValue;
var cancelNowCheck = false;

/**
 * Get browser size
 */
$.clientCoords = function() {
     var dimensions = {width: 0, height: 0};
     if (document.documentElement) {
         dimensions.width = document.documentElement.offsetWidth;
         dimensions.height = document.documentElement.offsetHeight;
     } else if (window.innerWidth && window.innerHeight) {
         dimensions.width = window.innerWidth;
         dimensions.height = window.innerHeight;
     }
     return dimensions;
}

/**
 * Set special values for using in javascript
 */
function setValues(arrValues) {
    // Path        
    webRoot = arrValues[0];
    // Language
    langCode = arrValues[1];
    // Rand value
    randValue = arrValues[2];
}

/**
 * When document full loaded and ready
 */
$(document).ready(function() {
 	$('[rel=external]').each(function() {
  		$(this).attr('target','_blank');
  	}); 
});

/**
 * Check proxies
 */
var intCountProxies; 

function cancelCheck(booCancel) {
    if (booCancel) {
        cancelNowCheck = true;
    } else {
        cancelNowCheck = false;
    }    
}

function checkProxyInput() {
    if (jQuery.trim($('#strProxyInput').val())) {
        var arrProxies = jQuery.trim($('#strProxyInput').val()).split('\n');
        if (arrProxies.length>30) {
            alert('No more than 30 proxies possible!');
            return false;
        }
        if (arrProxies.length>5) {
            if ($('#divCaptcha').height() > 0) {
                return true;
            } else {
                $('#divAd01').css('display','none');
                $('#divCaptcha').height(125);
                $('#divCaptcha').css('overflow','visible');
                return false;
            }
        } else {
            if ($('#divCaptcha').height() > 0) {
                $('#divCaptcha').height(0);
                $('#divCaptcha').css('overflow','hidden');
                $('#divAd01').css('display','block');
            }            
            return true;
        }
    } else {
        return false;
    }    
}

function startCheckProxies(startValue) {
    cancelCheck(false);
    intCountProxies = jQuery.trim($('#strProxyInput').val()).split('\n');
    intCountProxies = intCountProxies.length;
    if (intCountProxies>5) {
        $.post(webRoot+'/index.php', $("#formCheckProxies").serialize(), function(data) {
            if (data == 'ok') {
                startValue = randValue;    
                if (startValue == randValue) {
                    checkProgress(1);
                    disableCheckSite(1,'Start proxy check...');
                    window.setTimeout("checkProxies()", 500);
                }
            } else {
                alert(data.replace('error#',''));
            }
        });
        Recaptcha.reload();
    } else {
        startValue = randValue;
        if (startValue == randValue) {
            checkProgress(1);
            disableCheckSite(1,'Start proxy check...');
            window.setTimeout("checkProxies()", 500);
        }
    }
}
 
function checkProxies() {
    if (jQuery.trim($('#strProxyInput').val())) {
        var arrProxies = jQuery.trim($('#strProxyInput').val()).split('\n');
    } else {
        var arrProxies = new Array();    
    }
    var strType = $('#strType option:selected').val();
    var intTimeOut = $('#intTimeOut option:selected').val();
    if (arrProxies.length) {
        intA = 0;
        if (jQuery.trim(arrProxies[intA])) {
            checkProgress(Math.round(((intCountProxies-arrProxies.length)/intCountProxies)*100),'Check proxy '+arrProxies[intA]+' - Please wait... ');
            // Open proxy check
            $.ajax({
                type: 'POST',
                async: false,
                url: webRoot+'api/check.php',
                data: 'strProxy='+arrProxies[intA]+'&strType='+strType+'&intTimeOut='+intTimeOut,
                success: function(strResult) {
                    arrResult = strResult.split('#');
                    if (arrResult[0] == 'ok') {
                        $('#strUsableList').append(arrProxies[intA]+' » ('+arrResult[1]+', '+arrResult[3]+'s)');
                        $('#strUsableList').append(' from '+arrResult[2]);
                        $('#strUsableList').append('\r\n');
                    } else {
                        $('#strNotUsableList').append(arrProxies[intA]);
                        if (arrResult[1] == 'Timeout') {
                            $('#strNotUsableList').append(' (Timeout)');
                        }
                        if (arrResult[1] == 'Wrong ip/host syntax') {
                            $('#strNotUsableList').append(' (Wrong ip/host syntax)');
                        }                        
                        $('#strNotUsableList').append('\r\n');
                    }
                },
                error: function(strResult,errorText,errorCode) {
                    alert('('+errorCode+') '+errorText);
                    checkProgress(-1);                    
                    disableCheckSite(0);
                }                
            });
        }
        $('#strProxyInput').val(removeFirstLine($('#strProxyInput').val().split('\n')));
        if (cancelNowCheck == false) { 
            window.setTimeout("checkProxies()", 500);
        } else {
            checkProgress(-1);
            disableCheckSite(0);
        }
    } else {
        checkProgress(-1);
        disableCheckSite(0);
    }
}

/**
 * Disable check site 
 */
function disableCheckSite(booDisable) {
    if (booDisable == 1) {
        $('#strProxyInput').attr("disabled", true);    
        $('#strUsableList').attr("disabled", true);    
        $('#strNotUsableList').attr("disabled", true);    
        $("input[type='button']").attr("disabled", true);
        $('#btnCheckNow').css('display','none');
        $('#btnCancelCheck').css('display','block');
        $("#btnCancelCheck").removeAttr("disabled");    
    } else {
        $('#strProxyInput').removeAttr("disabled");    
        $('#strUsableList').removeAttr("disabled");    
        $('#strNotUsableList').removeAttr("disabled");    
        $("input[type='button']").removeAttr("disabled");    
        $('#btnCancelCheck').css('display','none');
        $('#btnCheckNow').css('display','block');
    }    
}

/**
 * Set check progress 
 */
function checkProgress(intPercent,strProxy) {
    if (intPercent >= 0) {
        $('#divShoutBoxShadow').css('display','block');
        $('#divShoutBoxShadow').css('opacity', 0.5);
        $('#divProgress').css('display','block');        
        if (intPercent == 0) {
            intPercent = 1;    
        }    
        $('#divProgressBar').width(intPercent+'%');
        $('#divProgressBarText').html(strProxy);
    } else {
        $('#divProgressBar').width('100%');
        $('#divProgressBarText').html('Finished...');
        window.setTimeout(function() {
            $('#divProgress').fadeOut('slow');    
            $('#divProgressBar').width('0%');
            $('#divShoutBoxShadow').css('display','none');
            $('#divCaptcha').css('display','none');
            $('#divAd01').css('display','block');
        },1000);
    }   
}

/**
 * Clear input 
 */
function clearInput(element) {
    element.val('');
}

/**
 * Remove the first line of a textarea 
 */
function removeFirstLine(arrProxys) {
    var tmpProxys = '';
    for (var i=1; i<=arrProxys.length-1; i++) {
        if (arrProxys[i] != '') {
            tmpProxys += arrProxys[i]+'\n';
        }
    } 
    return tmpProxys;  
}

/**
 * Filter IP or Hosts 
 */
function filterHost(element) {
    var content = element.val();
    
    while (content.match(/(: )|( :)/g)) {
        content = content.replace(': ',':');
        content = content.replace(' :',':');
    }
    
    var result1 = content.match(/\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:\d{2,5}\b/g);
    var result2 = content.match(/\b[a-z0-9-.]{2,}.[a-z0-9-]{2,4}:[0-9]{2,5}\b/g);
    var found = 0;
    var exp1,exp2,i,a,tmp;
  
    if ((result1) || (result2)) element.val('');

    if (result1) {
        for (i = 0; i < result1.length; ++i) {
            exp1 = result1[i].split(':');
            if (exp1[1] <= 65535) {
                var exp2 = exp1[0].split('.');
                if ((exp2[0] <= 255) && (exp2[1] <= 255) && (exp2[2] <= 255) && (exp2[3] <= 255)) {       
                    element.val(element.val()+result1[i]+'\n');
                    content = content.replace(result1[i],'');          
                    found = 1;
                }
            }
        } 
    }

    var result2 = content.match(/\b[a-z0-9-.]{2,}.[a-z0-9-]{2,4}:[0-9]{2,5}\b/g);

    if (result2) {
        for (i = 0; i < result2.length; ++i) {
            exp1 = result2[i].split(':');
            if (exp1[1] <= 65535) {     
                element.val(element.val()+result1[i]+'\n');
                content = content.replace(/result2[i]/g,'');          
                found = 1;
            }
        }  
    }  
    if (found == 0) {
        alert('No Proxies found.');    
    }
}

/**
 * Disable site
 */
function disableSite($booDisable) {
    if ($booDisable) {
        $("input[type='button']").attr("disabled", true);
        $('body').prepend('<div id="divDisable" style="top:0; left:0; position:absolute; width:100%; height:100%; z-index:100; background-color:#000;"></div>');
        $('#divDisable').css('opacity',0.5);
    } else {
        $('#divDisable').remove();
        $("input[type='button']").removeAttr("disabled");    
    }        
}

/**
 * 
 */
function showCaptcha() {
    disableSite(1);
    $('body').prepend('<div id="divCaptcha" style="top:30%; left:50%; margin:0 0 0 -160px; position:absolute; background-color:#fff; border:1px solid #000; padding:5px; z-index:101; text-align:right;"><div id="divCaptchaInput"></div></div>');
    Recaptcha.create('6LdHo7oSAAAAALN1gxokikTwGiR4hvUwdJpAY0iZ',
        'divCaptchaInput', {
            theme: 'white',
            tabindex: 0,
            callback: function() {
                alert(Recaptcha.get_response());
            }
        }
    );
    $('#divCaptcha').append('<input type="submit" name="btnCaptchaOk" id="btnCaptchaOk" value="Okay" style="font-weight:bold;" />');
    if ($('#btnCheckNow').length > 0) {
        $('#btnCaptchaOk').val($('#btnCheckNow').val());    
    }
}
 
