function doesFileExist(urlToFile){
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', urlToFile, false);
  xhr.send();

  if(xhr.status == "404"){
    //console.log("File doesn't exist");
    return false;
  }else{
    //console.log("File exists");
    return true;
  }
}
function checkSkip(param){
  var result = "";
  if(param == 1){
    result = "Yes";
  } else {
    result = "No";
  }
  return result;
}
function checkPublish(param){
  var result = "";
  if(param == 1){
    result = "Publish";
  } else {
    result = "Not Publish";
  }
  return result;
}
function getBatch(page){
    var view_page = 5;//banyakny page per view
    var batch = 1;
    var flag = false;
    while(!flag){
        if(page > view_page){
            view_page = view_page + 5;
            batch++;
        } else {
            flag = true;
        }
    }
    return batch;
}
function getFullMonth(param) {
  var month = param - 1;
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  return monthNames[month];
}
function formatDate(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
function charString(variable,length){
  variable = htmlspecialchars_decode(variable, 'ENT_QUOTES');
  var strDecode = strip_tags(variable,'<p>');
  strDecode = strip_tags(variable,'<div>');
  var strLength = strDecode.length;
  if(strLength > length){
  	var result = strDecode.substr(0, length)+"...";
  } else {
  	var result = strDecode;
  }
  return result;
}

function encode(variable){

  var regex = /\\/g;
  var replaceTitle = variable.replace(regex, "").replace(/&quot;/g, "");
  var lowercase = replaceTitle.toLowerCase();
  var result = lowercase.replace(/\s+/g, '-');

  return result;
}

function strip_tags(input, allowed){

	allowed = (((allowed || '') + '')
		.toLowerCase()
		.match(/<[a-z][a-z0-9]*>/g) || [])
    .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
    commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '')
    .replace(tags, function($0, $1) {
    	return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}
function htmlspecialchars_decode(string, quote_style) {
	var optTemp = 0,
	i = 0,
	noquotes = false;
	if (typeof quote_style === 'undefined') {
		quote_style = 2;
	}
	string = string.toString()
	.replace(/&lt;/g, '<')
	.replace(/&gt;/g, '>');
	var OPTS = {
		'ENT_NOQUOTES': 0,
		'ENT_HTML_QUOTE_SINGLE': 1,
		'ENT_HTML_QUOTE_DOUBLE': 2,
		'ENT_COMPAT': 2,
		'ENT_QUOTES': 3,
		'ENT_IGNORE': 4
	};
	if (quote_style === 0) {
		noquotes = true;
	}
          if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
          	quote_style = [].concat(quote_style);
          	for (i = 0; i < quote_style.length; i++) {
              // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
              if (OPTS[quote_style[i]] === 0) {
              	noquotes = true;
              } else if (OPTS[quote_style[i]]) {
              	optTemp = optTemp | OPTS[quote_style[i]];
              }
          }
          quote_style = optTemp;
      }
      if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
            string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
            // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
        }
        if (!noquotes) {
        	string = string.replace(/&quot;/g, '"');
        }
          // Put this in last place to avoid escape being double-decoded
          string = string.replace(/&amp;/g, '&');

          return string;
      }
function contentDisplay(varcontent,size){
  var resultContent = "";
  var content = "";
  var regex = /(<([^>]+)>)/ig;

  content = varcontent.replace(regex,"");
  variable = htmlspecialchars_decode(content, 'ENT_QUOTES');
  var strDecode = strip_tags(variable,'<p>');
  strDecode = strip_tags(variable,'<div>');
  strDecode = strip_tags(variable,'<img>');
  var strLength = strDecode.length;
  if(strLength > size){
    resultContent = strDecode.substr(0, size)+"...";
  } else {
    resultContent = strDecode;
  }

  return resultContent;
}
      function timeDifference(current, previous) {

      	var msPerMinute = 60 * 1000;
      	var msPerHour = msPerMinute * 60;
      	var msPerDay = msPerHour * 24;
      	var msPerMonth = msPerDay * 30;
      	var msPerYear = msPerDay * 365;

      	var elapsed = current - previous;

      	if (elapsed < msPerMinute) {
      		return Math.round(elapsed/1000) + ' SECONDS AGO';   
      	}

      	else if (elapsed < msPerHour) {
      		return Math.round(elapsed/msPerMinute) + ' MINUTES AGO';   
      	}

      	else if (elapsed < msPerDay ) {
      		return Math.round(elapsed/msPerHour ) + ' HOURS AGO';   
      	}

      	else if (elapsed < msPerMonth) {
      		return Math.round(elapsed/msPerDay) + ' DAYS AGO';   
      	}

      	else if (elapsed < msPerYear) {
      		return Math.round(elapsed/msPerMonth) + ' MONTHS AGO';   
      	}

      	else {
      		return Math.round(elapsed/msPerYear ) + ' YEARS AGO';   
      	}
      }

$.urlParam = function (name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  if (results == null) {
    return null;
  }
  else {
    return results[1] || 0;
  }
}

function sizeFile(file){
  return file.value != "" ? file.files[0].size : "";
}

var counter = 1;
var limit = 6;
var num = 1;

function addInput(divName){

  $("#error-photo-1").html("");
  $("#error-photo-1").hide();
  $("#input-photo-1").removeClass("input-error");
  if (counter == limit)  {
    alert("You may upload as many photos as you like, but you can only upload "+counter+" photos at a time.");
  } else {
    var newdiv = document.createElement('div');
    newdiv.id = "Photo"+ (num + 1);
    newdiv.innerHTML = "<br/>";
    newdiv.innerHTML += "<div class='hide photo-number'></div>";
    newdiv.innerHTML += "<input id='input-photo-"+(num + 1)+"' name='photo[]' type='file' class='file' style='display:inline-block;' onchange='checkSizeFile("+(num + 1)+")' /></div>";
    newdiv.innerHTML += "<input id='input-photo-size-"+(num + 1)+"' type='hidden'>";
    newdiv.innerHTML += "<a href='#js' title='remove field' onClick=\"removeInput('Photo" + (num + 1) + "');\" ><i class='fa fa-remove' style='color:#444;'></i></a>";
    newdiv.innerHTML += "<div id='error-photo-"+(num + 1)+"' class='is-error'></div>";
    document.getElementById(divName).appendChild(newdiv);
    counter++;
    num++;
  }
}

function removeInput(childId){
  var ele = document.getElementById(childId);

  var parentEle = document.getElementById('photoField');

  parentEle.removeChild(ele);
  counter--;
}
function checkFormatImage(value){
    var val = value.toLowerCase();
    var regex = new RegExp("(.*?)\.(jpg|jpeg|png|gif|svg)$");
    if(!(regex.test(val))){
        return false;
    }else{
        return true;
    }
}
function sizeFile(file){
    return file.value != "" ? file.files[0].size : "";
}
function checkFormatFile(value){
    var val = value.toLowerCase();
    var regex = new RegExp("(.*?)\.(jpg|jpeg|png|doc|docx|xls|xlsx|ppt|pptx|pdf|zip|rar)$");
    if(!(regex.test(val))){
        return false;
    }else{
        return true;
    }
}
function rowPhoto() {
    var tot_photo = $('.iphoto').length;
    $("#image-list").append(createPhotoForm(tot_photo));
};
function randomString() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
};
function createPhotoForm(onumber){
    var param_num = randomString();
    var resultHTML = "";
    resultHTML += "<div id='bar-imagej-"+param_num+"' class='form-group' style='width: 500px;'>";
    resultHTML += "<div class='input-group'>";
    resultHTML += "<span class='input-group-addon imageg-addon'>";
    resultHTML += "<input type='file' id='photoj-"+param_num+"' name='image[]' class='iphoto' >";
    resultHTML += "</span>";
    resultHTML += "<input type='text' id='ptitlej-"+param_num+"' name='ititle[]' class='form-control' placeholder='Image Title'>";
    resultHTML += "<span class='input-group-btn'>";
    resultHTML += "<a href='javascript:void(0);' onclick='deleteRowImage(&#39;"+param_num+"&#39;);' class='btn btn-danger'>";
    resultHTML += "<i class='fa fa-remove'></i>";
    resultHTML += "</a>";
    resultHTML += "</span>";
    resultHTML += "</div>";
    resultHTML += "</div>";
    return resultHTML;
};
function deleteRowImage(param){
    $("#bar-imagej-"+param).remove();
};
function setPrimary(param){
    $(".il-star").hide();
    $('input[name=imagePrimary]').attr('checked',false);
    $("#istar-"+param).show();
    $('#iprimary-'+param).attr('checked',true);
};
function setPrimaryPhoto(param){
    $(".il-star").hide();
    $('.iprimary').val('0');
    $("#istar-"+param).show();
    $('#iprimary-'+param).val('1');
};
//success alert
function successAlert(text){
  Command: toastr["success"](text)
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-right",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "300",
    "hideDuration": "1000",
    "timeOut": "8000",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  }
}
function successAlertTimer(text,time){
  Command: toastr["success"](text)
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-right",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "300",
    "hideDuration": "1000",
    "timeOut": time,
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  }
}
//error alert
function errorAlert(text){
  Command: toastr["error"](text)
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-right",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "300",
    "hideDuration": "1000",
    "timeOut": "8000",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  }
}
function errorAlertTimer(text,time){
  Command: toastr["error"](text)
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": false,
    "positionClass": "toast-top-right",
    "preventDuplicates": false,
    "onclick": null,
    "showDuration": "300",
    "hideDuration": "1000",
    "timeOut": time,
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  }
}
function formatRupiah(angka, prefix){
  var result = "";

  var number_string = angka.toString(),
    sisa  = number_string.length % 3,
    rupiah  = number_string.substr(0, sisa),
    ribuan  = number_string.substr(sisa).match(/\d{3}/g);
      
  if (ribuan) {
    separator = sisa ? '.' : '';
    rupiah += separator + ribuan.join('.');
  }
  result = prefix+rupiah;
  return result;
}