function emailForm(email) {
         var mailto_link = 'mailto:'+email;
         win = window.open(mailto_link,'emailWindow');
         if (win && win.open &&!win.closed) win.close();
} 

var Page = function() {
    this.mapScale = 14;
    this.loaderImage = new Image();
    this.loaderImage.src = '/styles/loading.gif';
    this.messages = new Array();
    this.ajaxResult = new Array();
    this.language = '';
    
    this.map = false;
    this.landingSubmit = 0;
    this.geocoder = false;
    this.mapIcon = '/styles/default/icon-flag.png';
}

Page.prototype.validate = function(formId) {
    var result = true;
    if($('#feedBackName').val().length == 0) {
        $('#feedBackName').parent().addClass('formSelected');
        result = false
    } else {
        $('#feedBackName').parent().removeClass('formSelected');
    }

    if($('#feedBackEmail').val().length == 0) {
        $('#feedBackEmail').parent().addClass('formSelected');
        result = false
    } else if(!$('#feedBackEmail').val().match(/^[a-zA-Z0-9\-\._]+@[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}/)) {иф
        $('#feedBackEmail').parent().addClass('formSelected');
        result = false
    } else {
        $('#feedBackEmail').parent().removeClass('formSelected');
    }

    if($('#feedBackPhone').val().length == 0) {
        $('#feedBackPhone').parent().addClass('formSelected');
        result = false
    } else {
        $('#feedBackPhone').parent().removeClass('formSelected');
    }

    if($('#feedBackText').val().length == 0) {
        $('#feedBackText').parent().addClass('textareaSelected');
        result = false
    } else {
        $('#feedBackText').parent().removeClass('textareaSelected');
    }
    return result;
}

Page.prototype.showAddress = function(address) {
  if(!address) {
        var address = $('#contactAddress').val();
        if(!address) {
            alert('Neuvedena adresa');
            return false;
        }
    }
    if(!this.map) {
        this.geocoder = new google.maps.Geocoder();
        $('#contactMap').css('display', 'block');
        var myOptions = {
          zoom: 7,//this.mapScale,
          disableDefaultUI: true,
          navigationControl:true,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        this.map = new google.maps.Map(document.getElementById('contactMap'), myOptions);
    }
    this.geocoder.geocode({"address": address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            Page.map.setCenter(results[0].geometry.location);
            if(!Page.marker) {
                Page.marker = new google.maps.Marker({
                    map: Page.map, 
                    position: results[0].geometry.location,
                    draggable: false
                });
            } else {
                Page.marker.setPosition(results[0].geometry.location);
            }
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
    });

}

Page.prototype.reloadCaptcha = function(imageId){
    if(document.getElementById(imageId)) {
        var image = document.getElementById(imageId);
    } else {
        return false;
    }
    image.parentNode.style.background = 'transparent url("' + this.loaderImage.src + '") no-repeat center center';
    image.style.visibility = 'hidden';
    image.onload = function() {
        this.style.visibility = 'visible';
        this.parentNode.style.background = 'none';
    };
    image.src = image.src.replace(/&nc=\d+/, '&nc='+(new String((new Date).getTime())).substr(8,5));
}

Page.prototype.commentReply = function(commentId){
    if(!this.commentHolder) {
        this.commentHolder = document.createElement('div');
        this.commentHolder.className = 'commentHolder';
        this.commentHolder.innerHTML = 'Váš nový komentář';
    }
    var comment = document.getElementById('comment' + commentId);
    if(!comment) return false;
    if(comment.nextSibling.nextSibling && comment.nextSibling.nextSibling.id) {
        comment.parentNode.insertBefore(this.commentHolder, comment.nextSibling.nextSibling);
    }
    else if(comment.nextSibling && comment.nextSibling.id) {
        comment.parentNode.insertBefore(this.commentHolder, comment.nextSibling);
    } else {
        comment.parentNode.appendChild(this.commentHolder);
    }
    document.getElementById('commentParent').value = commentId;
    
    //if(comment.nextSibling).tagName
    //comment.parentNode.insertAfter()
}

Page.prototype.articleVote = function(articleId, direction) {
      $.post("/ajax.php", {'action':'articleVote', 'articleId': articleId, 'direction': direction}, function(data){
            if (data>0) {
                  $('#voteValue'+articleId).html(data);
                  if($('#voteError'+articleId)) {
                        $('#voteError'+articleId).css('display', 'none');
                  }
                  if($('#voteOk'+articleId)) {
                        $('#voteOk'+articleId).css('display', 'block');
                  }
            } else {
                  if($('#voteError'+articleId)) {
                        $('#voteError'+articleId).css('display', 'block');
                        if(data) {
                             $('#voteError'+articleId).html(data);
                        }
                  }
                  if($('#voteOk'+articleId)) {
                        $('#voteOk'+articleId).css('display', 'none');
                  }
            }
      });
}

Page.prototype.switchFaqAnchor = function() {
    if(document.location.hash.indexOf('category') > -1 || document.location.hash.indexOf('answer') > -1) {
        if(document.location.hash.indexOf('answer') > -1) {
            var ansId = document.location.hash.replace('answer', '').replace('#', '') - 0;
            var catId = $('#faqAnswer' + ansId).parent().parent().attr('id').replace('faqCategory', '');
        } else {
            var catId = document.location.hash.replace('category', '').replace('#', '') - 0;
        }
        if(catId) {
            var item = $('#faqCategory'+catId);
            item.slideDown();
            while(item.parent().attr('id').indexOf('faqCategory') > -1) {
                item.parent().slideDown();
                item = item.parent();
            }
            document.location.hash = document.location.hash;
        }
    }
}

Page.prototype.testAdvertiserReg1 = function() {
    $("#reg").submit(function() {
        if ($("#submiting").val()==1) {
            return false;
        }
        //$urlInput = $('#reg .form-a input[name*="advertiser_domain_url"]').length ? $('#reg .form-a input[name*="advertiser_domain_url"]') : $('#reg .form-a input[name*="advertiser_domain_url"]')
        var url = $('#reg .form-a input[name*="_domain_url"]').val();
        if(!url || url.indexOf('http://') > -1) {
            return true;
        }
        $('#reg .form-a input[name*="_domain_url"]').val('http://' + url);
        return true;
    });
    $("#reg").validate({
      submitHandler: function(form) {
        $("#reg .create a").addClass('inactiveContinue');
        $('#reg .continue a').click(function(){return false;});
        $("#submiting").val(1);
         form.submit();
       },        
       rules: {
            'data[full_name]': "required",
            'agree': "required",
            'captcha': "required",
            'data[email]': {
                required: true,
                email: true
            },
            'data[passwd]': {
                required: true,
                minlength: 6
            },
            'data[passwd2]': {
                required: true,
                equalTo: "#formPassword"
            },
            'data[advertiser_domain_url]': {
                required: true,
                url: true
            },
            'data[supplier_domain_url]': {
                required: true,
                url: true
            }
        },
        messages: {
            'data[full_name]': this.messages['requiredName'],
            'captcha': this.messages['requiredCaptcha'],
            'agree': this.messages['requiredAgree'],
            'data[passwd]': {
                required: this.messages['required'],
                minlength: this.messages['passWeak']
            },
            'data[passwd2]': {
                required: this.messages['required'],
                equalTo: this.messages['passEqual']
            },
            'data[email]': {
                required: this.messages['required'],
                email: this.messages['requiredEmail']
            },
            'data[advertiser_domain_url]': {
                required: this.messages['required'],
                url: this.messages['incorrectUrl']
            },
            'data[supplier_domain_url]': {
                required: this.messages['required'],
                url: this.messages['incorrectUrl']
            }
        },
        highlight: function(element, errorClass) {
            if($(element).attr('id') == 'formCheckAgree') {
                $('.form-c').addClass('error');
            } else {
                $(element).parent().addClass('error');
            }
        },
        unhighlight: function(element, errorClass) {
            if($(element).attr('id') == 'formCheckAgree') {
                $('.form-c').removeClass('error');
            } else {
                $(element).parent().removeClass('error');
            }
            
        },    
        errorLabelContainer: "#errorBox"
    });
}

Page.prototype.testAdvertiserReg2 = function() {
    $("#reg").submit(function() {
            if ($("#submiting").val()==1) {
                return false;
            }
            var exist = new Array();
            var ok = true;
            var err = '';
            $('#reg .form-f input').each(function(cnt, el) {
                if(!el.value) {
                    return false;
                }
                if(typeof exist[el.value] == 'undefined') {
                    exist[el.value] = true;
                    $(el).parent().removeClass('error2');
                } else {
                    err += '<label class="error" for="' + el.name + '" generated="true">' + Page.messages['uniqueKw'].replace('#', el.value) + '</label>';
                    $(el).parent().addClass('error2');
                    $('#errorBox').show().delay(1000);
                    ok = false;
                }
            });
            $('#errorBox2').html(err);
            return ok;
    });
    $("#reg").validate({
    submitHandler: function(form) {
            if ($("#submiting").val()==1) {
                return false;
            }
        $("#reg .continue a").addClass('inactiveContinue');
        $('#reg .continue a').click(function(){return false;});
       form.submit();
        $("#submiting").val(1);
     },        
        rules: {
            'data[keyword][1]': "required",
            'data[keyword][2]': "required",
            'data[keyword][3]': "required",
            'data[keyword][4]': "required",
            'data[keyword][5]': "required",
            'data[url][1]': "required",
            'data[url][2]': "required",
            'data[url][3]': "required",
            'data[url][4]': "required",
            'data[url][5]': "required"
        },
        messages: {
            'data[keyword][1]': this.messages['requiredKw'],
            'data[keyword][2]': this.messages['requiredKw'],
            'data[keyword][3]': this.messages['requiredKw'],
            'data[keyword][4]': this.messages['requiredKw'],
            'data[keyword][5]': this.messages['requiredKw'],
            'data[url][1]': this.messages['requiredUrl'],
            'data[url][2]': this.messages['requiredUrl'],
            'data[url][3]': this.messages['requiredUrl'],
            'data[url][4]': this.messages['requiredUrl'],
            'data[url][5]': this.messages['requiredUrl']
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('error');
        },
        unhighlight: function(element, errorClass) {
            $(element).parent().removeClass('error');
        },    
        errorLabelContainer: "#errorBox"
    });
}


Page.prototype.testAdvertiserReg3 = function() {
    $("#reg").validate({
        rules: {
            'data[full_name]': "required",
            'data[town]': "required",
            'data[street]': "required",
            'data[zip]': "required"
        },
        messages: {
            'data[full_name]': this.messages['requiredCompany'],
            'data[town]': this.messages['requiredTown'],
            'data[street]': this.messages['requiredStreet'],
            'data[zip]': this.messages['requiredZip']
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('error');
        },
        unhighlight: function(element, errorClass) {
            $(element).parent().removeClass('error');
        },    
        errorLabelContainer: "#errorBox"
    });

    $("#reg").submit( function() {
        if(!$("#reg").valid()) {
            return false;
        }

        if($('#userType1').attr('checked')) {
            // Send company form
            var params = {
                'action':'saveUserCompany',
                'userType' : ($('#userType1').attr('checked') ? 1 : 0),
                'data[full_name]': $('#reg input[name*="full_name"]').val(),
                'data[country]': $('#reg select[name*="data[country]"]').val(),
                'data[state]': $('#reg select[name*="data[state]"]').val(),
                'data[town]': $('#reg input[name*="data[town]"]').val(),
                'data[street]': $('#reg input[name*="data[street]"]').val(),
                'data[zip]': $('#reg input[name*="data[zip]"]').val(),
                'data[ico]': $('#reg input[name*="data[ico]"]').val(),
                'data[dic]': $('#reg input[name*="data[dic]"]').val()
            };
            $.post("/ajax.php", params, function() {
                Page.payRegistration();
            });
        } else {
            Page.payRegistration();
        }
    
        return false;
    });
}

Page.prototype.payRegistration = function() {
    var amount = $('#paymentAmount').val() - 0;
    if(!amount) {
        $('#paymentAmount').parent().addClass('error');
        $('#paymentAmount').change(function() {
            $(this).parent().removeAttr('error');
        });
        $('#errorBox').append('<label class="error">' + Page.messages['requiredAmount'] + '</label>').show();
    } else {
        var currency = $('#currency').val();
        
        // Save selected payment method
        $.cookie('regStep3Payment', $('.types input[name="payment"]:checked').attr('id'));
        
        if($('#paymentPayPal').attr('checked')) {
            Page.payPayPal(amount, currency);
            
        } else if($('#paymentMoneybookers').attr('checked')) {
            Page.payMoneybookers('moneybookers', amount, currency);
        
        } else if($('#paymentMoneybookers').attr('checked') || $('#paymentCard').attr('checked')) {
            Page.payMoneybookers('card', amount, currency);
        
        } else {
            $.post("/ajax.php", {'action': 'getFilnalUrl'}, function(link) {
                document.location.href = link;
            });
        }
    }
}

Page.prototype.testNewsletter = function() {
    $("#nwlForm").validate({
        rules: {
            'captcha': 'required',
            'email': {
                required: true,
                email: true
            }
        },
        messages: {
            'captcha': Page.messages['requiredCaptcha'],
            'email': {
                required: Page.messages['required'],
                email: Page.messages['requiredEmail']
            }
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('error');
        },
        unhighlight: function(element, errorClass) {
            $(element).parent().removeClass('error');
        },    
        errorLabelContainer: "#errorBox"
    });
}

Page.prototype.testAgencyForm = function() {
    $("#form").validate({
        rules: {
            'data[company]': 'required',
            'data[name]': 'required',
            'data[surname]': 'required',
            'data[phone]': 'required',
            'data[text]': 'required',
            'captcha': 'required',
            'data[email]': {
                required: true,
                email: true
            }
        },
        messages: {
            'data[company]': Page.messages['required'],
            'data[name]': Page.messages['required'],
            'data[surname]': Page.messages['required'],
            'data[phone]': Page.messages['required'],
            'data[text]': Page.messages['required'],
            'captcha': Page.messages['requiredCaptcha'],
            'data[email]': {
                required: Page.messages['required'],
                email: Page.messages['requiredEmail']
            }
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('error');
        },
        unhighlight: function(element, errorClass) {
            $(element).parent().removeClass('error');
        },    
        errorLabelContainer: "#errorBox"
    });
}

Page.prototype.switchCompanyForm = function(direction) {
    if(!direction) {
        $('#companyData').hide();
        $('#companyData input').attr('disabled', 'disabled');
        if ($('#regYourNameLabel').length) {
            $('#regYourNameLabel').html('Your name:');
        }
    } else {
        $('#companyData').show();
        $('#companyData input').removeAttr('disabled');
        if ($('#regYourNameLabel').length) {
            $('#regYourNameLabel').html('Company name:');
        }
    }
    $('#userType' + direction).attr('checked', 'checked');
}

Page.prototype.createPopup = function(holder, text) {
    $(holder).CreateBubblePopup({
        innerHtml: text,
        width: 230,
        position: 'top',
        distance: 20,
        align: 'center',
        themeName: 'all-black',
        themePath: '/styles/default/jquerybubblepopup-theme'
    });
}

Page.prototype.payPayPal = function(amount, currency) {
    $.post("/ajax.php", {'action': 'getPaymentData', 'method': 'PayPal', 'amount': amount, 'currency': currency}, function(link) {
        document.location.href = link;
    });
}

Page.prototype.payMoneybookers = function(method, amount, currency) {
    $.post("/ajax.php", {'action': 'getPaymentData', 'method': method, 'amount': amount, 'currency': currency}, function(form) {
        $('#mother').append(form);
        $('#moneybookersForm').submit();
    });
}

Page.prototype.copyLink = function() {
    ZeroClipboard.setMoviePath( "/js/ZeroClipboard10.swf" );
    var clip = new ZeroClipboard.Client();
    clip.setText( $('#copyText').val() );
    clip.glue( "copyClipboard" );
}

Page.prototype.equalHeight = function(group, fixUl) {
     var tallest = 0;
     group.each(function() {
            var thisHeight = $(this).height();
            if(thisHeight > tallest) {
                 tallest = thisHeight;
            }
     });
     if(fixUl) {
         fixUl.height((tallest - 65) + 'px');
     }
     group.height(tallest);
}

Page.prototype.formatPrice = function(val) {
    return new String(val).replace(/(.{3})/, '$1');
}

Page.prototype.correctPrice = function(val, currency, currencyFrom) {
    var result = 0;

    switch(currencyFrom) {
        case 'USD': result = val * this.exchangeRates.USD; break;
        case 'EUR': result = val * this.exchangeRates.EUR; break;
        default:    result = val;
    }
    switch(currency) {
        case 'USD': result = result / this.exchangeRates.USD; break;
        case 'EUR': result = result / this.exchangeRates.EUR; break;
        default:    result = result;
    }
    return Math.round(result, 4);
}

Page.prototype.calcAgencies = function() {
    if(typeof this.language == 'undefined') {
        return false;
    }
    var webCount = $('#calcWebCount').val() - 0;
    if(!webCount) {
        $('#calcWebCount').val(10);
        webCount = 10;
        
    }
    var linksCount = $('#calcLinks').val() - 0;
    if(!linksCount) {
        $('#calcLinks').val(50);
        linksCount = 50;
        
    }
    var timeLink = $('#calcTimeLink').val() - 0;
    if(!timeLink) {
        $('#timeLink').val(30);
        timeLink = 30;
    }
    var monthBuilder = $('#calcMonthBuilder').val() - 0;
    if(!monthBuilder) {
        $('#calcMonthBuilder').val(this.formatPrice(1500));
        monthBuilder = 1500;
    }
    if(this.language == 'en') {
        monthBuilder = this.correctPrice(monthBuilder, 'CZK', 'USD');
    } else if(this.language == 'sk') {
        monthBuilder = this.correctPrice(monthBuilder, 'CZK', 'EUR');
    } else {
        monthBuilder = this.correctPrice(monthBuilder, 'CZK', 'CZK');
    }
    var resTime = Math.ceil((webCount * linksCount * timeLink) / 60);
    $('#calcResTime').html(this.formatPrice(resTime));
    
    var priceBg = Math.ceil((webCount * linksCount) * this.correctPrice(10));
    if(this.language == 'en') {
        priceBg = this.correctPrice(priceBg, 'USD');
    } else if(this.language == 'sk') {
        priceBg = this.correctPrice(priceBg, 'EUR');
    }
    $('#calcResPrice').html(this.formatPrice(priceBg));
    
    var PriceTotal = Math.ceil(resTime / 160 * monthBuilder);
    if(this.language == 'en') {
        PriceTotal = this.correctPrice(PriceTotal, 'USD');
    } else if(this.language == 'sk') {
        PriceTotal = this.correctPrice(PriceTotal, 'EUR');
    } else {
    }
    PriceTotal = PriceTotal - priceBg;

    $('#calcResFinal').html(this.formatPrice(PriceTotal));
}


Page.prototype.calcAdvertiser = function() {
    var links= $('input[name*=links]').val() - 0;
    if(!links || links < 0) {
        links = 10;
        $('input[name*=links]').val(links);
    }
    var pr = $('input[name*=pr]').val() - 0;
    if(pr<0 || pr>10) {
        pr = 3;
        $('input[name*=pr]').val(pr);
    }
    var age = $('input[name*=age]').val() - 0;
    if(!age || age<0) {
        age = 6;
        $('input[name*=age]').val(age);
    }
    var pages = $('input[name*=pages]').val() - 0;
    if(!pages || pages<1) {
        pages = 100;
        $('input[name*=pages]').val(pages);
    }
    
    var params = {
        'action':'calcAdvertiser',
        'links':links,
        'pr': pr,
        'age': age,
        'pages': pages
    }
    
    $('p.total input').val('. . . ');
    $.post("/ajax.php", params, function(data){
        if (data) {
            $('p.total input').val(data);
        }
    });    
    /* JS version of calculaor - deprecated
    pr = this.calc.googlePrValues[pr] - 0
    pages = (pages > this.calc.idealArticleCount ? this.calc.idealArticleCount : pages) / this.calc.idealArticleCount;
    age = (this.calc.daysPerMonth * age);
    age = (age > this.calc.idealDomainAge ? this.calc.idealDomainAge : age) / this.calc.idealDomainAge;
    
    // var pricePerArticle = this.calc.daysPerMonth * $googlePr * 
    */
}

Page.prototype.calcBlogger = function() {
    var articles= $('input[name*=artcnt]').val() - 0;
    if(!articles || articles < 0) {
        articles = 500;
        $('input[name*=artcnt]').val(articles);
    }
    var pr = $('input[name*=google_pr]').val() - 0;
    if(pr<0 || pr>10) {
        pr = 5;
        $('input[name*=google_pr]').val(pr);
    }
    var age = $('input[name*=age]').val() - 0;
    if(!age || age<0) {
        age = 36;
        $('input[name*=age]').val(age);
    }
    
    var params = {
        'action':'calcBlogger',
        'articles':articles,
        'pr': pr,
        'age': age
    }
    
    $('p.total input').val('. . . ');
    $.post("/ajax.php", params, function(data){
        if (data) {
            $('p.total input').val(data);
        }
    });    
}

Page.prototype.calcAffilate = function() {
    var type = $('#calcType').val();
    if(type == 'blogger') {
        var bloggers1 = $('input[name*=bloggers1]').val() - 0;
        if(!bloggers1 || bloggers1 < 0) {
            bloggers1 = 10;
            $('input[name*=bloggers1]').val(bloggers1);
        }
        var bloggers2 = $('input[name*=bloggers2]').val() - 0;
        if(bloggers2 < 0) {
            bloggers2 = 10;
            $('input[name*=bloggers2]').val(bloggers2);
        }
        var bloggers3 = $('input[name*=bloggers3]').val() - 0;
        if(bloggers3 < 0) {
            bloggers3 = 10;
            $('input[name*=bloggers3]').val(bloggers3);
        }
        var earn = $('input[name*=earn]').val() - 0;
        if(!earn || earn<0) {
            earn = 10000;
            $('input[name*=earn]').val(earn);
        }
        var params = {
            'action':'calcAffilateBlogger',
            'bloggers1':bloggers1,
            'bloggers2':bloggers2,
            'bloggers3':bloggers3,
            'earn': earn
        }
    } else {
        var publishers= $('input[name*=publishers]').val() - 0;
        if(!publishers || publishers < 0) {
            publishers = 10;
            $('input[name*=publishers]').val(publishers);
        }
        var spent = $('input[name*=spent]').val() - 0;
        if(!spent || spent<0) {
            spent = 3000;
            $('input[name*=spent]').val(spent);
        }        
        var params = {
            'action':'calcAffilateAdvertiser',
            'publishers':publishers,
            'spent': spent
        }
    }
    
    $('p.total input').val('. . . ');
    $.post("/ajax.php", params, function(data){
        if (data) {
            $('p.total input').val(data);
        }
    });    
}

Page.prototype.checkMiminumAmount = function(input, min, message) {
    if((($(input).val() - 0) < min) && message) {
        alert(message);
        $(input).val(min);
    } 
}

Page.prototype.sendEmail = function(text) {
    var win = window.open('mailto:'+Base64.decode(text), 'emailWindow');
    win.close();
}

Page.prototype.setDefaultPayment = function() {
    var c = $.cookie('regStep3Payment');
    if(c && $('#'+c)) {
        $('#'+c).attr('checked', 'checked');
    }
}

Page.prototype.showAffilateBanners = function() {
    var cnt = 0;
    //var clips = new Array();
    var clip;
    ZeroClipboard.setMoviePath( "/js/ZeroClipboard10.swf" );
    $('#content-in p:first a').each(function(){
        if($(this).attr('href').indexOf('http://') == -1) {
             $(this).attr('href', 'http://' + document.location.host + $(this).attr('href'));
        }
        $(this).html($(this).html().replace(/#.*$/, ''));
        //var code = $(this).clone().wrap('<div></div>').parent().html();
        var code = $(this).attr('href');
        // 890
        var text = '<div style="width:420px; float:left;"><input type="text" name="" id="affilateLink1" value=\'' + code.replace('\'', '"') + '\' style="width:420px;" readonly="readonly" /><br />';
        text += '(<a href="javascript:void(0);" class="affilateLinkCopy" id="affilateLinkCopy1">' + Page.messages.copyAffilateLink + '</a>)</div>';
        text += '<div style="width:60px; float:left; text-align:center; font-weight:bold;">' + Page.messages['or'] + '</div>';
        text += '<div style="width:420px; float:left;"><input type="text" name="" id="affilateLink2" value=\'' + code.replace('\'', '"').replace('#', 'a/') + '\' style="width:420px;" readonly="readonly" /><br />';
        text += '(<a href="javascript:void(0);" class="affilateLinkCopy" id="affilateLinkCopy2">' + Page.messages.copyAffilateLink + '</a>)</div>';
        text += '<div class="cleaner"></div>';
        $(this).replaceWith(text);

        clip = new ZeroClipboard.Client();
        clip.setText( $('#affilateLink1').val() );
        clip.glue( "affilateLinkCopy1" );
        clip = new ZeroClipboard.Client();
        clip.setText( $('#affilateLink2').val() );
        clip.glue( "affilateLinkCopy2" );
        //clips.push(clip);
    });
    $('#content-in p a img').each(function(){
        //console.log(this.src);
        if($(this).parent().attr('href').indexOf('http://') == -1) {
             $(this).parent().attr('href', 'http://' + document.location.host + $(this).parent().attr('href'));
             $(this).attr('src', 'http://' + document.location.host + $(this).attr('src'));
        }
        var code = $(this).parent().clone().wrap('<div></div>').parent().html();
        if($(this).width() <= 200) {
            $(this).parent().parent().addClass('affilateBannerVertical');
        }
        //console.log($(this).width());
        var text = '<div class="affilateBannerCode"><textarea id="affilateBannerCode' + cnt + '" readonly="readonly" >' + code + '</textarea><br />';
        text += '(<a hreg="javascript:void();" class="affilateBannerCopy" id="affilateBannerCopy' + cnt  + '">' + Page.messages.copyBannersCode + '</a>)</div>';
        $(this).parent().parent().prepend(text);
        
        clip = new ZeroClipboard.Client();
        clip.setText( $('#affilateBannerCode' + cnt).val() );
        clip.glue( 'affilateBannerCopy' + cnt );
        //clips.push(clip);
        ++cnt;
    });
    /*
    for(var i=0; i<clips.length - 1; i++) {
        clips[i].reposition();
    }
    */
}

Page.prototype.onload = function() {
    $("#lang ul").hide();
    $('#lang .active').click(function() {
        $('#lang ul').slideToggle(200);
        return false;
    });
    Page.equalHeight($(".category .in"));
    Page.equalHeight($(".home-box .in"), $("#help.home-box .in ul:first"));
    $(".blue-long .in,.yellow-long .in").hide();
    $(".blue-long h3,.yellow-long h3").click(function(){
        $(this).toggleClass("active").next().slideToggle(400);
    });

    $(function() {
        $( ".slider" ).slider({"min":1, "max":100, "value":10, "change": function(event, ui) {
            $('#calcWebCount').val(ui.value);
            Page.calcAgencies();
        }});
    });
    // Affilate hash
    if ( document.location.hash.match(/#[a-f0-9]{32}/) ) {
        var aff = document.location.hash;
        document.cookie = "affiliate="+aff.replace('#', '')+"; expires=1904303080;";
        $(document).ready(function() {
            $('#en').attr('href', $('#en').attr('href') + aff);
            $('#cs').attr('href', $('#cs').attr('href') + aff);
            $('#sk').attr('href', $('#sk').attr('href') + aff);
        });
    }
}

Page.prototype.addBonus = function(value) {
    var curr = $('.crr').html();
    $('p.bonus strong:first').html(Math.round(value*1.1) + ' ' + curr);
    $('p.bonus cite').html(Math.round(value*0.1) + ' ' + curr);
}

Page.prototype.changeContinent = function(url, value) {
    if(url && !value) {
        return false;
    }
    url = url ? url : document.location.href.replace(/ct\.\d+/, '')
    document.location.href = url + 'ct.' + (value-0) + '/';
}

Page.prototype.changeContinentList = function(value) {
    if(countries2Continents) {
        var selectedCountry = $('#list select[name="country_id"]').val();
        for(var country in countries2Continents) {
            if(countries2Continents[country] == value) {
                $('#list select[name="country_id"] option[value="' + country + '"]').show();
            } else {
                $('#list select[name="country_id"] option[value="' + country + '"]').hide();
                if(country == selectedCountry) {
                    $('#list select[name="country_id"]').val(0);
                }
            }
        }
    }
}

Page.prototype.changeCountry = function(url, value) {
    if(url && !value) {
        return false;
    }
    url = url ? url : document.location.href.replace(/ct\.\d+/, '')
    document.location.href = url + 'cn.' + (value-0) + '/';
}

Page.prototype.changeSpecialization = function(url, value) {
    if(url && !value) {
        return false;
    }
    url = url ? url : document.location.href.replace(/ct\.\d+/, '')
    document.location.href = url + 'sp.' + (value-0) + '/';
}

Page.prototype.searchPartners = function() {
    var continent = $('select[name=continent_id]').val();
    var country = $('select[name=country_id]').val();
    var specialization = $('select[name=specialization_id]').val();
    
    var url = document.location.pathname;
    url = url.replace(/\/ct\.\d+/, '');
    url = url.replace(/\/cn\.\d+/, '');
    url = url.replace(/\/sp\.\d+/, '');
    url = url.replace(/\/$/, '') + '/';
    
    if(continent) {
        url += 'ct.' + continent + '/';
    }
    if(country) {
        url += 'cn.' + country + '/';
    }
    if(specialization) {
        url += 'sp.' + specialization + '/';
    }
    document.location.href = url;
}

Page.prototype.prepareMapPartners = function(points) {
    if(!this.map) {
        this.geocoder = new google.maps.Geocoder();
        var myOptions = {
            zoom: 8,
            maxZoom:9,
            minZoom:2,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        this.map = new google.maps.Map(document.getElementById('map'), myOptions);
    }
}

Page.prototype.drawMapText = function(text, points) {
    this.prepareMapPartners();
    this.geocoder.geocode( { 'address': text}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            Page.map.fitBounds(results[0].geometry.bounds);
            Page.map.setZoom(Page.map.getZoom()+1);
            Page.drawPoints(points);
        } else {
            Page.drawMapPoints(points);
        }
    });
}

Page.prototype.drawMapPoints = function(points) {
    this.prepareMapPartners();

    var bounds = new google.maps.LatLngBounds;
    var point;
    for(var i=0; i<points.length; i++) {
        point = new google.maps.LatLng(points[i].lat, points[i].lng);
        bounds.extend(point);
    }
    this.map.fitBounds(bounds);
    Page.drawPoints(points);
}



Page.prototype.drawPoints = function(points) {
    for(var i=0; i<points.length; i++) {
        point = new google.maps.LatLng(points[i].lat, points[i].lng);
        var marker = new google.maps.Marker({
            map: Page.map,
            icon: Page.mapIcon,
            position: point,
            title: points[i].title,
            partnerId: points[i].id
        });
        google.maps.event.addListener(marker, 'click', function() {
            document.location.hash = 'partner' + this.partnerId;
        });
    }
}

/*landing page*/

Page.prototype.testAdvertiserRegLanding1 = function() {
    $("#reg").submit(function() {
            if ($("#submiting").val()==1) {
                return false;
            }
            var exist = new Array();
            var ok = true;
            var err = '';
            $('#reg .spanF input').each(function(cnt, el) {
                if(!el.value) {
                    return false;
                }
                if(typeof exist[el.value] == 'undefined') {
                    exist[el.value] = true;
                    $(el).parent().removeClass('error2');
                } else {
                    err += '<label class="error" for="' + el.name + '" generated="true">' + Page.messages['uniqueKw'].replace('#', el.value) + '</label>';
                    $(el).parent().addClass('error2');
                    $('#errorBox').show().delay(1000);
                    ok = false;
                }
            });
            $('#errorBox2').html(err);
            return ok;
    });
    $("#reg").validate({
        submitHandler: function(form) {
            if ($("#submiting").val()==1) {
                return false;
            }
        $("#reg .continue a").addClass('inactiveContinue');
        $('#reg .continue a').click(function(){return false;});
        form.submit();
        $("#submiting").val(1);
     },        
        rules: {
            'captcha': "required",
            'data[keyword][1]': "required",
            'data[keyword][2]': "required",
            'data[keyword][3]': "required",
            'data[keyword][4]': "required",
            'data[keyword][5]': "required",
            'data[url][1]': {required:true,url:true},
            'data[url][2]': {required:true,url:true},
            'data[url][3]': {required:true,url:true},
            'data[url][4]': {required:true,url:true},
            'data[url][5]': {required:true,url:true}
        },
        messages: {
            'data[keyword][1]': this.messages['requiredKw'],
            'data[keyword][2]': this.messages['requiredKw'],
            'data[keyword][3]': this.messages['requiredKw'],
            'data[keyword][4]': this.messages['requiredKw'],
            'data[keyword][5]': this.messages['requiredKw'],
            'data[url][1]': {required:this.messages['requiredUrl'],url:'Must be URL'},
            'data[url][2]': {required:this.messages['requiredUrl'],url:'Must be URL'},
            'data[url][3]': {required:this.messages['requiredUrl'],url:'Must be URL'},
            'data[url][4]': {required:this.messages['requiredUrl'],url:'Must be URL'},
            'data[url][5]': {required:this.messages['requiredUrl'],url:'Must be URL'}
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('error');
        },
        unhighlight: function(element, errorClass) {
            $(element).parent().removeClass('error');
        },    
        errorLabelContainer: "#errorBox"
    });
}

Page.prototype.testAdvertiserRegLanding2 = function() {
    $("#reg").validate({
        rules: {
            'data[full_name]': "required",
            'data[email]': {
                required: true,
                email: true
            },
            'data[passwd]': {
                required: true,
                minlength: 6
            },
            'data[passwd2]': {
                required: true,
                equalTo: "#formPassword"
            }
        },
        messages: {
            'data[full_name]': 'Copmany or Your name must be filled',
            'data[email]': 'Email must be filled',
            'data[passwd]': 'Your password length must be min. 6 characters',
            'data[passwd2]': 'Your password length must be min. 6 characters'
        },
        highlight: function(element, errorClass) {
            $(element).parent().addClass('error');
        },
        unhighlight: function(element, errorClass) {
            $(element).parent().removeClass('error');
        },    
        errorLabelContainer: "#errorBox"
    });

    $("#reg").submit( function() {
        if(!$("#reg").valid()) {
            return false;
        }
        if (Page.landingSubmit == 1) {
            $("#reg .continue a").addClass('inactiveContinue');
            $('#reg .continue a').click(function(){return false;});
            var params = {
                'action':'landingSubmit1',
                'data[full_name]': $('#reg input[name*="full_name"]').val(),
                'data[email]': $('#reg input[name*="data[email]"]').val(),
                'data[passwd]': $('#reg input[name*="data[passwd]"]').val(),
                'data[passwd2]': $('#reg input[name*="data[passwd2]"]').val(),
                'data[country]': $('#reg select[name*="data[country]"]').val()
            };
            $.post("/ajax.php", params, function(result) {
                r = jQuery.parseJSON( result );
                if (r.id > 0) {
                    Page.landingSubmit = 10;
                    $("#reg .continue a").removeClass('inactiveContinue');
                    $('#reg .continue a').click(function(){$('#reg').submit()});
                    var params = {
                        'action':'landingSubmit2'
                    };
                    $.post("/ajax.php", params, function() {
                        return false;
                    });

                } else {
                    alert("Please change your e-mail, this e-mail already exists!");
                }
                return false;
            });
        } else {
            if($('#userType1').attr('checked') && Page.landingSubmit==10) {
                // Send company form
                var params = {
                    'action':'saveUserCompany',
                    'userType' : ($('#userType1').attr('checked') ? 1 : 0),
                    'data[full_name]': $('#reg input[name*="full_name"]').val(),
                    'data[country]': $('#reg select[name*="data[country]"]').val(),
                    'data[state]': $('#reg select[name*="data[state]"]').val(),
                    'data[town]': $('#reg input[name*="data[town]"]').val(),
                    'data[street]': $('#reg input[name*="data[street]"]').val(),
                    'data[zip]': $('#reg input[name*="data[zip]"]').val(),
                    'data[ico]': $('#reg input[name*="data[ico]"]').val(),
                    'data[dic]': $('#reg input[name*="data[dic]"]').val()
                };
                $.post("/ajax.php", params, function() {
                     Page.payRegistration();
                });
            } else {
                if (Page.landingSubmit==10) {
                    Page.payRegistration();
                }    
            }
        }  
        return false;
    });
}

var Page = new Page();
$(document).ready(function(){ 
    Page.onload();
});

/* FROM Coder  */
Cufon.replace ('h2,h3,h4,#motto,.feat .image span, .feat-right .image span,#sure .in ol li',{fontFamily: 'Aeroportal Bold'});
Cufon.replace ('h1,.tab',{fontFamily: 'Aeroportal Bold',textShadow: '1px 1px rgba(0, 0, 0, 0.5)'});
Cufon.replace ('#header-right .login, .category .join a, #list .submit a, .back a, #news li a, .try a, #right .box h3, #calc a, .join a, #agencies .submit a, .create a, .contact a, .login-blg a, #recom .email, #recom .facebook, #recom .twitter, .login-adv a, .continue a, p.contact, a.btn',{fontFamily: 'Aeroportal Bold',textShadow: '1px 1px rgba(0, 0, 0, 0.5)'});
Cufon.replace ('#lang a',{fontFamily: 'Aeroportal Bold',textShadow: '1px 1px rgba(0, 0, 0, 0.5)',hover: true});
Cufon.replace ('#sub h1',{fontFamily: 'Aeroportal Bold',textShadow: false});

