$(document).ready(function(){
    $('input[name=Email]').each(function(){$(this).blur(function(){remove_spaces(this)})});
    $('input[name=txtEmail]').each(function(){$(this).blur(function(){remove_spaces(this)})});
    lable_check_event ();
});
function include_once( filename, callback ) {
    var cur_file = {};
    cur_file[window.location.href] = 1;
 
    if (!window.php_js) window.php_js = {};
    if (!window.php_js.includes) window.php_js.includes = cur_file;
    if (!window.php_js.includes[filename]) {
        if(include(filename, callback)){
            return true;
        }
    } else{
        return true;
    }
}

function include( filename, callback) { 
    var js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', filename);
    if(callback)
        js.onload = callback;
    document.getElementsByTagName('HEAD')[0].appendChild(js);
 
    // save include state for reference by include_once
    var cur_file = {};
    cur_file[window.location.href] = 1;
 
    if (!window.php_js) window.php_js = {};
    if (!window.php_js.includes) window.php_js.includes = cur_file;
    if (!window.php_js.includes[filename]) {
        window.php_js.includes[filename] = 1;
    } else {
        window.php_js.includes[filename]++;
    }
 
    return window.php_js.includes[filename];
}
function number_format( number, decimals, dec_point, thousands_sep ) { 
    var n = number, prec = decimals;
 
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
 
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
 
    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}
function include_facebook(lang, cid){
    var callback = function(){
            if(typeof facebook_init == 'function') {                
                facebook_init();
            } else {
                setTimeout(callback,1000);
            }
        };
    include_once("/common/js/fbconnect.js.php?lang="+lang+"&cid="+cid);
    callback();
}
function remove_spaces(elm) {
    $(elm).val($(elm).val().replace(/\s/g,''));
}
function lable_check_event () {
    $('label[for]').each(
            function(){
                var id = $(this).attr('for');
                $(this).click(
                        function(){
                            var type = $('#'+id).attr('type');
                            if ($('#'+id).get(0) && 'checkbox' == type && true == $('#'+id).get(0).checked) {
                                $('#'+id).get(0).checked = false;
                            } else {
                                if ($('#'+id).get(0))
                                    $('#'+id).get(0).checked = true;
                            }
                        }
                        );
            }
            );
}
function getArgs() {
    var args = new Object();
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split("&");                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos + 1);    // Extract the value
        value = decodeURIComponent(value);        // Decode it, if needed
        args[argname] = value;                    // Store as a property
    }
    return args;                                  // Return the object
}
function in_array(needle, haystack, argStrict) {
    var found = false, key, strict = !!argStrict; 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    } 
    return found;
}
function CustomIcons(checkboxHeight, radioHeight, selectWidth) {
    
    checkboxHeight = checkboxHeight?checkboxHeight:"25";
    radioHeight = radioHeight?radioHeight:"25";
    selectWidth = selectWidth?selectWidth:"190";
    
    document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; }</style>');

    var Custom = {
        init: function() {
            var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
            for(a = 0; a < inputs.length; a++) {
                if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
                    span[a] = document.createElement("span");
                    span[a].className = inputs[a].type;

                    if(inputs[a].checked == true) {
                        if(inputs[a].type == "checkbox") {
                            position = "0 -" + (checkboxHeight*2) + "px";
                            span[a].style.backgroundPosition = position;
                        } else {
                            position = "0 -" + (radioHeight*2) + "px";
                            span[a].style.backgroundPosition = position;
                        }
                    }
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    $(inputs[a]).change(Custom.clear);
                    $(inputs[a]).click(Custom.clear);
                    span[a].onmousedown = Custom.pushed;
                    span[a].onmouseup = Custom.check;
                    $(span[a]).click(inputs[a].onclick);
                    document.onmouseup = Custom.clear;
                }
            }
            inputs = document.getElementsByTagName("select");
            for(a = 0; a < inputs.length; a++) {
                if(inputs[a].className == "styled") {
                    option = inputs[a].getElementsByTagName("option");
                    active = option[0].childNodes[0].nodeValue;
                    textnode = document.createTextNode(active);
                    for(b = 0; b < option.length; b++) {
                        if(option[b].selected == true) {
                            textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
                        }
                    }
                    span[a] = document.createElement("span");
                    span[a].className = "select";
                    span[a].id = "select" + inputs[a].name;
                    span[a].appendChild(textnode);
                    inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                    inputs[a].onchange = Custom.choose;
                }
            }
        },
        pushed: function() {
            element = this.nextSibling;
            if(element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
            } else if(element.checked == true && element.type == "radio") {
                this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
            } else if(element.checked != true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
            } else {
                this.style.backgroundPosition = "0 -" + radioHeight + "px";
            }
        },
        check: function() {
            element = this.nextSibling;
            if(element.checked == true && element.type == "checkbox") {
                this.style.backgroundPosition = "0 0";
                element.checked = false;
            } else {
                if(element.type == "checkbox") {
                    this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
                } else {
                    this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
                    group = this.nextSibling.name;
                    inputs = document.getElementsByTagName("input");
                    for(a = 0; a < inputs.length; a++) {
                        if(inputs[a].name == group && inputs[a] != this.nextSibling) {
                            inputs[a].previousSibling.style.backgroundPosition = "0 0";
                        }
                    }
                }
                element.checked = true;
            }
        },
        clear: function() {
            inputs = document.getElementsByTagName("input");
            for(var b = 0; b < inputs.length; b++) {
                if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
                } else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                } else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
                } else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
                    inputs[b].previousSibling.style.backgroundPosition = "0 0";
                }
            }
        },
        choose: function() {
            option = this.getElementsByTagName("option");
            for(d = 0; d < option.length; d++) {
                if(option[d].selected == true) {
                    document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
                }
            }
        }
    }
    $(document).ready(function(){Custom.init();});
}
function defaultJsCountrySelect(srcItem)
{
    var postcodes = document.getElementsByName('Postcode');
    if (postcodes.length)
        $.post('/act/index.php?r=ajaxCheckCountry', {country: srcItem.value},
                                    function (data) 
                                    {
                                        var postcode = document.getElementsByName('Postcode')[0];
                                        if (data!='1')
                                        {
                                            postcode.disabled = true;
                                            postcode.style.background = '#ddd';
                                        } else
                                        {
                                            postcode.disabled = false;
                                            postcode.style.background = 'none';
                                        } 
                                    });
}
var http_request = false;
function makePOSTRequest(url, parameters) {
   http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
         // set type accordingly to anticipated content type
         //http_request.overrideMimeType('text/xml');
         http_request.overrideMimeType('text/html');
      }
   } else if (window.ActiveXObject) { // IE
      try {
         http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {}
      }
   }
   if (!http_request) {
      alert('Cannot create XMLHTTP instance');
      return false;
   }
   
   http_request.onreadystatechange = alertContents;
   http_request.open('POST', url, true);
   http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http_request.setRequestHeader("Content-length", parameters.length);
   http_request.setRequestHeader("Connection", "close");
   http_request.send(parameters);
}

function alertContents() {
   if (http_request.readyState == 4) {
      if (http_request.status == 200) {
         //alert(http_request.responseText);
         result = http_request.responseText;
         document.getElementById('formcontainer').innerHTML = result;            
      } else {
         alert('There was a problem with the request.');
      }
   }
}

function get(obj) {
 if (document.getElementById("Email").value == '') {
     alert("Email is Required"); 
 } else {    
      var poststr = "FirstName=" + encodeURI( document.getElementById("FirstName").value ) +
                     "&LastName=" + encodeURI( document.getElementById("LastName").value ) +
                     "&Email=" + encodeURI( document.getElementById("Email").value ) +
                     "&Cell=" + encodeURI( document.getElementById("Cell").value ) +
                     "&Postcode=" + encodeURI( document.getElementById("Postcode").value ) +
                     "&Country=" + encodeURI( document.getElementById("Country").value ) +
                     "&ThankYouSubject=" + encodeURI( document.getElementById("ThankYouSubject").value )+
                     "&ThankYouBody=" + encodeURI( document.getElementById("ThankYouBody").value )+
                     "&SendTo=" + encodeURI( document.getElementById("SendTo").value )+
                     "&cid=" + encodeURI( document.getElementById("cid").value )+
                     "&lang=" + encodeURI( document.getElementById("lang").value )+
                     "&EmailFromName=" + encodeURI( document.getElementById("EmailFromName").value )+
                     "&EmailFrom=" + encodeURI( document.getElementById("EmailFrom").value ); 
       makePOSTRequest('/act/ajaxact.php', poststr);
 }
}

function addNewRowForFile()
{

var tbl = document.getElementById('myTable');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
row.setAttribute('id', iteration);
row.className = '';

// cell 1
var cell1 = row.insertCell(0);
cell1.setAttribute('align', 'center');

var num_ = iteration+1;
cell1.innerHTML = 'Photo '+num_ +':';


var cell2 = row.insertCell(1);
var el = document.createElement('input');
el.setAttribute('type', 'file');
el.setAttribute('name', 'file' + iteration );
el.setAttribute('id', 'file' + iteration);
//el.className = 'input100proc';
cell2.appendChild(el);


}
function stats_send(_cid)
{
jQuery.post('/act/ajax_send_stats.php',{campaign_id: encodeURI( _cid )});
}

window.fCopyToClipboard = function(rSource){
    rSource.select();
    return 0;
}
function CountDown(
        TargetDate,
        DisplayFormat,
        ElementId,
        LeadingZero
    )
{
    this.TargetDate = TargetDate;
    this.LeadingZero = true;
    this.DisplayFormat = DisplayFormat;
    this.ElementId = ElementId;
 
    this.calcage = function(secs, num1, num2) {
        s = ((Math.floor(secs / 1000 / num1)) % num2).toString();
        if (self.LeadingZero && s.length < 2)
            s = '0' + s;
        return '<b>' + s + '</b>';
    };
 
    this.CountBack = function() {
        this.secs = this.dstDate - new Date().valueOf();
        if (this.secs < 0) {
            this.Element.innerHTML = '';
            return;
        }
        var DisplayStr = this.DisplayFormat;
        var DisplayStr = DisplayStr.replace(/%%D%%/g, this.calcage(this.secs, 86400, 100000));
        DisplayStr = DisplayStr.replace(/%%H%%/g, this.calcage(this.secs, 3600, 24));
        DisplayStr = DisplayStr.replace(/%%M%%/g, this.calcage(this.secs, 60, 60));
        DisplayStr = DisplayStr.replace(/%%S%%/g, this.calcage(this.secs, 1, 60));
        DisplayStr = DisplayStr.replace(/%%FH%%/g, this.calcage(this.secs, 3600, 100000));
        DisplayStr = DisplayStr.replace(/%%\F\M%%/g, this.calcage(this.secs, 60, 100000000000));
        DisplayStr = DisplayStr.replace(/%%FS%%/g, this.calcage(this.secs, 1, 10000000000000));
        this.Element.innerHTML = DisplayStr;
        obj = this;
        setTimeout(function() { obj.CountBack(); }, 1000);
    };
 
 
    this.Element = document.getElementById(this.ElementId);
    this.dstDate = new Date(this.TargetDate).valueOf();
    this.CountBack();
}
function Counter(max2, max, data_id, progress_id, ajax_data ){
    this.max2 = max2;
    this.max = max;
    this.num = arguments[5]?arguments[5]:0;
    this.timerId;
    this.plus = 1;
    this.timeout = 0;
    this.data_id = data_id;
    this.progress_id = progress_id;
    this.proc = 211 / this.max2;
    this.ajax_counter_timer;
    this.ajax_data = ajax_data;
    var counter = this;
    if(this.max > this.max2){
        this.proc = 211 / this.max;
    }
    this.showCounter = function(){
        var k = new Number();
        document.getElementById(counter.data_id).innerHTML = ''+counter.addCommas(counter.num);
        element = document.getElementById(counter.progress_id);  
        element.style.width = parseInt(counter.proc * counter.num)+'px';
    }
    this.getSumm = function (nnm, nnm2)
    {
        var rand;
        if(nnm2<10)
        {
            rand = nnm + 1
            timeout = 100;
        }
        else if(nnm2<100)
        {
            rand = nnm + Math.floor((Math.random()*9)+1);
            timeout = 0;
        }
        else if(nnm2<1000)
        {
            rand  = nnm + Math.floor((Math.random()*91)+10);
            timeout = 50;
        }
        else if(nnm2 < 10000)
        {
            rand  = nnm + Math.floor((Math.random()*901)+100);
            timeout = 50;                       
        }
        else if(nnm2 < 100000)
        {
            rand  = nnm + Math.floor((Math.random()*2001)+1000);
            timeout = 50;                   
        }
        else if(nnm2 < 1000000)
        {
            rand  = nnm + Math.floor((Math.random()*10001)+1000);
            timeout = 50;                   
        }
        else if(nnm2 <= 10000000)
        {
            rand  = nnm + Math.floor((Math.random()*100000)+10000);
            timeout = 50;               
        }
        else
        {
            rand = nnm + counter.plus;
        }
        return rand;
    }
    this.startCounter = function()
    {
        var rand;
        counter.showCounter();
        if(counter.timerId) 
        {
            clearTimeout(counter.timerId);      
        }
        if (counter.num < counter.max)
        {
            rand = counter.getSumm(counter.num, counter.max);   
            if(rand > counter.max)
            {
                var num2 = counter.max - counter.num;
                counter.num = counter.getSumm(counter.num, num2);           
            }
            else
            {
                counter.num = rand;         
            }       
            counter.timerId = setTimeout(counter.startCounter, timeout);
        } else if (counter.ajax_data && true == counter.ajax_data.ajax) {
            counter.ajaxCounter();
        }
            
    }
    this.addCommas = function(nStr)
    {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }
    this.ajaxCounter = function() {
        if(counter.ajax_counter_timer) {
            clearTimeout(counter.ajax_counter_timer);
        }
        $.getJSON('/act/ajax_counter.php', {cid: counter.ajax_data.cid, type: counter.ajax_data.template}, function (json) {
            if (0 == json.paused) {
                switch (counter.ajax_data.template) {
                    case 'donates':
                        if (in_array(counter.ajax_data.currencies, ['euro', 'euro_dollar'])) {
                            counter.max = json.EUR;
                        } else {
                            counter.max = json.USD;
                        }
                        $('#counter_text_'+counter.ajax_data.key).html(counter.get_donate_html(counter.ajax_data.currencies, json.USD, json.EUR));
                        break;
                    case 'donations':
                        counter.max = json.donations;
                        $('#counter_text_'+counter.ajax_data.key).html(number_format(json.donations) + '&nbsp;');
                        break;
                    case 'sign':
                        counter.max = json.count;
                        $('#counter_text_'+counter.ajax_data.key).html(number_format(json.count) + '&nbsp;');
                        break;
                }
            }
            counter.ajax_data.ajax = false;
            counter.startCounter();
            counter.ajax_counter_timer = setTimeout(counter.ajaxCounter, 5000);
        });
    };
    this.get_donate_html = function(type, usd, euro) {
        var html = '';
        switch (type) {
            case 'euro_dollar':
                html = "&euro;"+number_format(euro)+"&nbsp;( $ "+number_format(usd)+" )";
                break;
            case 'dollar_euro':
                html = "$"+number_format(usd)+"&nbsp;( &euro; "+number_format(euro)+" )";
                break;
            case 'dollar':
                html = "$"+number_format(usd)+"&nbsp;";
                break;
            case 'euro':
                html = "&euro;"+number_format(euro)+"&nbsp;";
                break;
        }
        return html;
    };
    this.startCounter();
}

/////////////////PRETTY DATE/////////////////////////
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
/////////////////////END OF PRETTY DATE//////////////////////////////