var hide_alerts = document.getElementById("hide_alerts");
if (hide_alerts !== null) {
	var myApp = new Framework7({ fastClicks:false, cache:false, swipeBackPage:false, notificationHold:7000, animatePages:false, pushState: true, onAjaxStart: function(xhr) { myApp.showIndicator(); }, onAjaxComplete: function(xhr) { myApp.hideIndicator(); } });
} else {
	var myApp = new Framework7({ fastClicks:false, cache:false, swipeBackPage:false, animatePages:false, pushState: true, onAjaxStart: function(xhr) { myApp.showIndicator(); }, onAjaxComplete: function(xhr) { myApp.hideIndicator(); } });
}
var bgm;
var $$=Dom7;
var leftView=myApp.addView('.view-left',{dynamicNavbar:true});
var mainView=myApp.addView('.view-main',{dynamicNavbar:true});
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-70477-48', 'auto');
ga('send', 'pageview');
//$$(document).on('page:beforeanimation', function (e) { 
	//playSound("menu2");
//});
$$(document).on('onPageBeforeInit', function (e) { 
	//console.log("page load");
});
$$(document).on('pageInit', function (e) { 
    var page = e.detail.page;
    
    $('#homebtn').attr("disabled", false);
    $('#sidehome').attr("disabled", false);
    //console.log(page.name);
    
    if (page.name == 'register') {
        $.getScript("js/register.js");
        $.getScript("https://www.google.com/recaptcha/api.js");
    } else if (page.name == 'login') {
        $.getScript("js/login.js");
    } else if (page.name == 'forgot') {
        $.getScript("js/forgot.js");
    } else if (page.name == 'wiki') {
        $.getScript("js/wiki.js");
    } else if (page.name == 'profile') {
        $.getScript("js/profile.js");
        $.getScript("js/clipboard.min.js");
        new ClipboardJS('.sharelink');
    } else if (page.name == 'createcharacter') {
        $.getScript("js/createcharacter.js");
    } else if (page.name == 'changelocation') {
        $.getScript("js/changelocation.js");
    } else if (page.name == 'battle') {
	    
      $('#homebtn').attr("disabled", true);
      $('#sidehome').attr("disabled", true);
	    if (typeof actionfix !== "undefined"){ 
	    	clearInterval(actionfix);
	    }
	    
        if ($$(page.container).find('#confetti').data("enabled") == "true") {
	        //drawConfetti();
	        
	        setTimeout(function(){ 
		        $('.page-on-left').remove();
		        
		        	setTimeout(function(){	
				drawConfettiRibbon(); 
				//drawFireworks(); 
				}, 200);
		        }, 200);
        }
        
         var lock = 0;
         
         getStats();
         
         //$$(".actionswrapper").click(function(){if($(".actions").is(":visible")){}else{$(".actions").slideDown("fast");}});
         
		 
		    function runAttack(data) {
          mainView.router.loadContent(data);
          lock = 0;
          myApp.hidePreloader();
        }
			
			
			
			$$(".attacklink").click(function() {
			    var x = 0;//event.clientX;     // Get the horizontal coordinate
          var y = 0;//event.clientY;     // Get the vertical coordinate
          var coor = x + "," + y;
          if (!lock) {
			        lock = 1;
					    myApp.hideIndicator();
					
			        //playSound("attack");
			        $(".actions").fadeOut(0, function() {
				        $(this).remove();
				      });
			        method = "";
			        var enemyguid = $$(this).data("enemyguid");
			        if (enemyguid) {
			            $$.post('battle.php', {
			                guid: enemyguid, coor: coor
			            }, function(data) {
			                setTimeout(runAttack(data), 0)
			            }, function() {
			                //console.log("failure")
			            })
			        }
			    }
			    
			    $(this).attr('disabled', true);
			});
      $$(".remedylink").click(function() {
			    if (!lock) {
			        lock = 1;
					    myApp.hideIndicator();
					
			        //playSound("attack");
			        $(".actions").fadeOut(150, function() {
				        $(this).remove();
				    });
			        method = "";
			        var enemyguid = $$(this).data("enemyguid");
			        if (enemyguid) {
			            $$.post('battle.php?rm=1', {
			                guid: enemyguid
			            }, function(data) {
			                setTimeout(runAttack(data), 500)
			            }, function() {
			                //console.log("failure")
			            })
			        }
			    }
			    
			    $(this).attr('disabled', true);
			});
			$$(".speciallink").click(function() {
			    if (!lock) {
			        lock = 1;
					    myApp.hideIndicator();
					
			        //playSound("attack");
			        $(".actions").fadeOut(300, function() {
				        $(this).remove();
				    });
			        method = "";
			        var enemyguid = $$(this).data("enemyguid");
			        if (enemyguid) {
			            $$.post('battle.php?special=1', {
			                guid: enemyguid
			            }, function(data) {
			                setTimeout(runAttack(data), 1500)
			            }, function() {
			                //console.log("failure")
			            })
			        }
			    }
			    
			    $(this).attr('disabled', true);
			});
			$$(".heavylink").click(function() {
			    if (!lock) {
			        lock = 1;
					    myApp.hideIndicator();
					
			        //playSound("attack");
			        $(".actions").fadeOut(450, function() {
				        $(this).remove();
				    });
			        method = "";
			        var enemyguid = $$(this).data("enemyguid");
			        if (enemyguid) {
			            $$.post('battle.php?heavy=1', {
			                guid: enemyguid
			            }, function(data) {
			                setTimeout(runAttack(data), 3000)
			            }, function() {
			                //console.log("failure")
			            })
			        }
			    }
			    
			    $(this).attr('disabled', true);
			});
			$$(".superlink").click(function() {
			    if (!lock) {
			        lock = 1;
					    myApp.hideIndicator();
					
			        //playSound("attack");
			        $(".actions").fadeOut(450, function() {
				        $(this).remove();
				    });
			        method = "";
			        var enemyguid = $$(this).data("enemyguid");
			        if (enemyguid) {
			            $$.post('battle.php?super=1', {
			                guid: enemyguid
			            }, function(data) {
			                setTimeout(runAttack(data), 3000)
			            }, function() {
			                //console.log("failure")
			            })
			        }
			    }
			    $(this).attr('disabled', true);
			});
			$$(".coverlink").click(function() {
			    if (!lock) {
			        lock = 1;
					//myApp.showPreloader();
					
			        method = "";
			        var enemyguid = $$(this).data("enemyguid");
			        if (enemyguid) {
			            $$.post('battle.php?cover=1', {
			                guid: enemyguid
			            }, function(data) {
			                setTimeout(runAttack(data), 300)
			            }, function() {
			                //console.log("failure")
			            })
			        }
			    }
			    $(this).attr('disabled', true);
			});
			$$(".runlink").click(function() {
			    if (!lock) {
			        lock = 1;
			        method = "hideenemy";
			        var enemy_id = $$(this).data("enemyguid");
			        $.ajax({
			            url: "worker.php?go=" + method + "&id=" + enemy_id,
			            method: "POST"
			        }).done(function(data) {
			            //console.log('success');
			        });
			        mainView.router.load({
			            url: "patrol.php",
			            force: true,
			            ignoreCache: true
			        });
			    }
			    $(this).attr('disabled', true);
			});
			$$(".patrollink").click(function() {
					method = "healcharacter";
					$.ajax({
							url: "worker.php?go=" + method,
							method: "POST"
					}).done(function(data) {
							//console.log('success');
					});
					mainView.router.load({
							url: "patrol.php",
							force: true,
							ignoreCache: true
					});
			});
					 
		  if ($$(page.container).find('#skip_battle_results').data("enabled") == "true") {
        //console.log('back to patrol2');
        
        setTimeout(function(){ $$(".patrollink").click(); }, 50);
      }
         
          
        // main show
		$(".actions").slideDown("fast");
         
         
         actionfix = setInterval(function(){ if ($(".actions").length == 0) { $$(".attacklink").click(); } else { } }, 3000);
         
         
    } else if (page.name == 'vendor') {
        $.getScript("js/vendor.js");
    } else if (page.name == 'changeweapon') {
        $.getScript("js/changeweapon.js");
    } else if (page.name == 'changearmor') {
        $.getScript("js/changearmor.js");
    } else if (page.name == 'patrol') {
        $.getScript("js/patrol.js");
        $$('.popupact').on('click', function () {
          myApp.popup('.popup-actions');
        });
        $.getScript("https://www.google.com/recaptcha/api.js");
    } else if (page.name == 'changesubclass') {
        $.getScript("js/changesubclass.js");
    } else if (page.name == 'inventory') {
        $.getScript("js/inventory.js");
    } else if (page.name == 'index-1') {
        $.getScript("js/index.js");
				checkBGMusic();
    } else if (page.name == 'logout') {
        $.getScript("js/logout.js");
    } else if (page.name == 'settings') {
        $.getScript("js/settings.js");
    } else if (page.name == 'message') {
        $.getScript("js/message.js");
    } else if (page.name == 'clan') {
        $.getScript("js/clan.js");
    } else if (page.name == 'findclan') {
        $.getScript("js/findclan.js");
    } else if (page.name == 'viewclan') {
        $.getScript("js/findclan.js");
    } else if (page.name == 'messages') {
        $.getScript("js/messages.js");
    } else if (page.name == 'sendmessage') {
        $.getScript("js/sendmessage.js");
    }  else if (page.name == 'gear') {
        $.getScript("js/gear.js");
    }  else if (page.name == 'players') {
        $.getScript("js/players.js");
    }  else if (page.name == 'infusion') {
        $.getScript("js/infusion.js");
    } else if (page.name == 'sellitems') {
        $.getScript("js/sellitems.js");
    } else if (page.name == 'grimoire') {
        $.getScript("js/grimoire.js");
    } else if (page.name == 'leaderboards') {
        $.getScript("js/leaderboards.js");
    } else if (page.name == 'convertac') {
        $.getScript("js/convert.js");
    } else if (page.name == 'guardian') {
        var char_id = $('#char_id').html();
        $.getScript("js/guardian.php?char_id="+char_id);
    } else if (page.name == 'customize') {
        $.getScript("js/customize.js");
    } else if (page.name == 'story') {
        $.getScript("js/story.js");
    } else if (page.name == 'editstory') {
        $.getScript("js/editstory.js");
    } else if (page.name == 'stats') {
        $.getScript("js/stats.php");
    } else if (page.name == 'settlement') {
        $.getScript("js/settlement.js");
    } else if (page.name == 'give') {
        $.getScript("js/give.js");
    } else if (page.name == 'shop') {
        $.getScript("js/shop.js");
    } else if (page.name == 'forum') {
		$.getScript("js/forum.js");
	} else if (page.name == 'daily') {
        var user_id = $('#user_id').html();
        $.getScript("js/daily.php?user_id="+user_id);
    } else if (page.name == 'transpose') {
        $.getScript("js/transpose.js");
    } else if (page.name == 'resetchar') {
        $.getScript("js/resetchar.js");
    } else if (page.name == 'clantitles') {
        $.getScript("js/clantitles.js");
    } else if (page.name == 'hourlystats') {
        $.getScript("js/hourlystats.js");
    } else if (page.name == 'changename') {
        $.getScript("js/changename.js");
    } else if (page.name == 'iosiap') {
        $.getScript("js/iosiap.js");
    } else if (page.name == 'delaccount') {
        $.getScript("js/delaccount.js");
    } else if (page.name == 'upgrade') {
        ga('send', {
          hitType: 'event',
          eventCategory: 'Section',
          eventAction: 'Coin Store',
          eventLabel: 'AC'
        });
    }
	
	// track
    //ga('send', 'event', 'Subsection', e.detail.page.name, 'Titan Conquest');
    //ga('send', 'pageview');
	
    /*
    var humanRNG = getRandomizer(1, 5000);
    if (humanRNG == 7) {
    	myApp.alert("If you are not a robot, click OK!", 'Robot Check!');
	}
	*/
	$("#actions").slideDown("fast");
	
	//console.log("fired");
});
function getRandomizer(bottom, top) {
    return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
function startBgMusic() {
	//bgm = document.getElementById("bg");
	
	var bgdiv = document.getElementById("bgm");
	
	if (bgdiv !== null) {
		bgm = new Audio('mp3/bg.mp3'); 
		
		if (bgm != null) {
			bgm.loop=true;
			bgm.volume=0.05;
			bgm.play();
			checkBGMusic();	
		}
	}
}
function pauseBgMusic() {
	var bgdiv = document.getElementById("bgm");
	if (bgdiv !== null) {
		if (bgm != null) {
			bgm.pause();
      bgm.currentTime = 0.0;
			bgm = null;
			checkBGMusic();
		}
	}
}
function checkBGMusic() {
	
	if (bgm != null) {
		if (bgm.paused) {
			$$("#playbgm").show();
  		$$("#pausebgm").hide();
		} else {
			$$("#playbgm").hide();
  		$$("#pausebgm").show();
		}
	}
}
function playSound(obj) {
	snd = document.getElementById(obj);
	if (snd != null) snd.play();
}
// always need this
$.getScript("js/index.js");
$$(".mainlink").click(function() { 
	window.location = "index.php";
});
$$("#playbgm").click(function() { 
	startBgMusic();
	$$("#playbgm").hide();
  $$("#pausebgm").show();
});
$$("#pausebgm").click(function() { 
	pauseBgMusic();
	$$("#playbgm").show();
  $$("#pausebgm").hide();
});
$$('.panel-right').on('open', function () {
    doCWFC("chatlastcheck", "");
    $("#openchatbtn").removeClass("button-highlight");
    $("#openchatbtn").hide();
});
$$('.panel-right').on('close', function () {
	doCWFC("chatlastcheck", "");
    $("#openchatbtn").removeClass("button-highlight");
    $("#openchatbtn").show();
});
function scrollTo(target) {
	$('.page-content').animate({
        scrollTop: $("#"+target).offset().top
    }, 500);
}
function scrollToDiv(div) {
	$('.page-content').animate({scrollTop:$("#"+div).offset().top - 100}, 500);
}
// chat
$('#chat_txt_mobile').keypress(function(event) {
    if (event.keyCode == 13) {
       event.preventDefault();
       text = $(this).val();
       room = $("#chatroom_mobile").val();
       
       $('#chat_txt_mobile').val("");
	   $('#chat_txt_mobile').focus();
	   
	   $.ajax({
	    	url: "worker.php?go=addchat&text="+encodeURIComponent(text)+"&room="+encodeURIComponent(room),
			method: "POST"
	    })
		.done(function(data) {
			$("#openchatbtn").removeClass("button-highlight");
			getChatD();
	  	});
	   
    }   
});
$('#chat_txt_desktop').keypress(function(event) {
    if (event.keyCode == 13) {
       event.preventDefault();
       text = $(this).val();
       room = $("#chatroom_desktop").val();
       
       //console.log(room)
       
       $('#chat_txt_desktop').val("");
	   $('#chat_txt_desktop').focus();
	   
	   $.ajax({
	    	url: "worker.php?go=addchat&text="+encodeURIComponent(text)+"&room="+encodeURIComponent(room),
			method: "POST"
	    })
		.done(function(data) {
			getChatD();
	  	});
	   
    }   
});
$('.chatroom').change(function(e) {
	var room = $( this ).val();
	var last = $( this ).data("last");
	
	//console.log(last);
	
	$("#chat_room_last").val($(".chatroom").val())
	
	if (room == "custom") {
		// ask them
		myApp.prompt('Enter a room name', 'Custom Chat', 
	      function (value) {
		      
		      var room = value.trim();
          room = room.replace(/<(.|\n)*?>/g, '');
		      //console.log(room);
            
            
		      if (room) {
		        $('.chatroom').append('');
		        $("#chatroom_desktop").val(room);
				$("#chatroom_mobile").val(room);
				getChatD();
			  } else {
				$("#chatroom_desktop").val("global");
				$("#chatroom_mobile").val("global");
				getChatD();
			  }
	      },
	      function (value) {
	        // cancel
	        $("#chatroom_desktop").val("global");
			    $("#chatroom_mobile").val("global");
			    getChatD();
	      }
		);	
	}
	
	// synch
	$("#chatroom_desktop").val(room);
	$("#chatroom_mobile").val(room);
	
	$(".chatflip").show();
	$( this ).data("last", room);
	$("#chat_room_last").val(last);
	
	getChatD();
});
$(".chatflip").click(function() {
	var last = $("#chat_room_last").val();
	
	$("#chat_room_last").val($(".chatroom").val())
	
	$("#chatroom_desktop").val(last);
	$("#chatroom_mobile").val(last);	
	
	//console.log(last + " " + $("#chat_room_last").val());
	
	// remove highlight
	$(".chatflip").addClass("chatflipG");
	$(".chatflip").removeClass("chatflipY");
	
	doCWFC("chatlastcheck", "");
	getChatD();
});
function setChatRoom(room) {
	
	// add if not there
	if ($('.chatroom option:contains('+ room +')').length == 0 && room != "staff" && room != "clan") {
		$('.chatroom').append('');
	}
	
	// change them
	$("#chatroom_desktop").val(room);
	$("#chatroom_mobile").val(room);
  doCWFC("chatlastcheck", ""); 
  $(".chatflip").show();          
	getChatD();
	
	//console.log("room is now "+room);
}
function getChatD() {
	setTimeout(function() { getChat() }, 200);
}
function getChat() {
	var randomnumber=Math.floor(Math.random()*500000);
	
	room = $(".chatroom").val();
	
	if($("#chatzoneDesktop").is(":visible")){
	    $('#chatzoneDesktop').load('worker.php?cachebuster='+randomnumber+'&go=getchat&room='+encodeURIComponent(room), function() {
			linkCQD();
		});
	} else {
		$('#chatzoneMobile').load('worker.php?cachebuster='+randomnumber+'&go=getchat&room='+encodeURIComponent(room), function() {
			linkCQM();
		});
	}
}
function linkCQD() {
	$('.cq').click(function() {
		var un = $(this).data('username');
		$("#chat_txt_desktop").val("@"+un+": ");
		$("#chat_txt_desktop").focus();
		//console.log(un);
	});
}
function linkCQM() {
	$('.cq').click(function() {
		var un = $(this).data('username');
		$("#chat_txt_mobile").val("@"+un+": ");
		$("#chat_txt_mobile").focus();
		//console.log(un);
	});
}
function checkChat() {
	
	room = $(".chatroom").val();
	
	$.ajax({
    	url: "worker.php?go=newchatscount&room="+encodeURIComponent(room),
		method: "POST"
    })
	.done(function(data) {
    	if (data != "0") {
	    	$("#openchatbtn").addClass("button-highlight");
    	}
  	});
  	
  	// bolt flip switch check
  	checkBoltChat();
}
function checkBoltChat() {
	room = $("#chat_room_last").val();
	
	$.ajax({
    	url: "worker.php?go=newchatscount&room="+encodeURIComponent(room),
		method: "POST"
    })
	.done(function(data) {
		//console.log("d "+data+" "+room);
    	if (data != "0") {
	    	$(".chatflip").addClass("chatflipY");
	    	$(".chatflip").removeClass("chatflipG");
    	}
  	});
}
function delChat(id) {
	$.ajax({
    	url: "worker.php?go=delchat&id="+id,
		method: "POST"
    })
	.done(function(data) {
    	getChatD();
  	});
}
function undelChat(id) {
	$.ajax({
    	url: "worker.php?go=undelchat&id="+id,
		method: "POST"
    })
	.done(function(data) {
    	getChatD();
  	});
}
function flagChat(id) {
	
  method = "flagchat";
  if (id > 0) {
		
		var buttons = [
			{
				text: 'Alert staff about this chat message?',
				label: true
			},
			{
				text: 'Yes',
				onClick: function () {
					
					$.ajax({
						url: "worker.php?go="+method+"&id="+id,
						  method: "POST"
					})
					.done(function(data) {
						
						//console.log('success', data);
						
						switch(data) {
							
							case "success":	    		
									
									myApp.alert("Staff has been alerted!", 'Success!');
								
								break;
						}
						
					  });
					
				}
			},
			{
				text: 'Cancel',
				color: 'red',
				onClick: function () {
					
				}
			},
		];
		myApp.actions(buttons);
	}
}
function getStats() {
	var randomnumber=Math.floor(Math.random()*500000);
	
	$('#statszone').load('worker.php?cachebuster='+randomnumber+'&go=getstats', function() {
            
	});
}
function doCWFC(content, options) {
	var randomnumber=Math.floor(Math.random()*500000);
	
	$.ajax({
    	url: "worker.php?go="+content+""+options,
		method: "POST"
    })
	.done(function(data) {
    	// console.log('success', data) 
    	//return data;
  	});
	
	//return "";
}
function claimChat(id) {
	$.ajax({
		url: "worker.php?go=claimchat&id="+id,
		method: "POST"
	})
	.done(function(data) {
		getChat();
	});
}
function checkForAlerts() {
	$.ajax({
    	url: "worker.php?go=alerts",
		method: "POST"
    })
	.done(function(data) {
    	if (data != "none") {
	    	alertUser(data);
    	}
  	});
}
function alertUser(text) {
	
	myApp.addNotification({
        title: 'Titan Conquest',
        message: text,
        onClose: function () {
            //myApp.alert('Notification closed');
        }
    });
}
var myPhotoBrowserPopupDark = myApp.photoBrowser({
    photos : [
        'https://titanconquest.com/img/screen1.png',
        'https://titanconquest.com/img/screen2.png',
        'https://titanconquest.com/img/screen3.png',
        'https://titanconquest.com/img/screen4.png'
    ],
    theme: 'dark',
    type: 'standalone'
});
$$('.pb-popup-dark-desktop').on('click', function () {
    myPhotoBrowserPopupDark.open();
}); 
var myPhotoBrowserPopupDark2 = myApp.photoBrowser({
    photos : [
        'https://titanconquest.com/img/screen1.png',
        'https://titanconquest.com/img/screen2.png',
        'https://titanconquest.com/img/screen3.png',
        'https://titanconquest.com/img/screen4.png'
    ],
    theme: 'dark',
    type: 'standalone'
});
$$('.pb-popup-dark-mobile').on('click', function () {
    myPhotoBrowserPopupDark2.open();
}); 
setInterval(checkForAlerts, 40000);
var chat_on = $("#chat_on").val();
if (chat_on == 1) {
	setInterval(getChat, 15000);
	setInterval(checkChat, 40000);
}
setInterval(getStats, 240000);
getChat();
getStats();
checkForAlerts();
setTimeout(function() { startBgMusic() }, 1000);
            
$$('.popover-xp').on('popover:open', function () {
  var randomnumber=Math.floor(Math.random()*500000);
	
	$('#pop_xp_content').load('worker.php?cachebuster='+randomnumber+'&go=getpopup&type=xp', function() {            
        
  });
});
            
$$('.popover-dr').on('popover:open', function () {
  var randomnumber=Math.floor(Math.random()*500000);
	
	$('#pop_dr_content').load('worker.php?cachebuster='+randomnumber+'&go=getpopup&type=dr', function() {            
        
  });
});
            
            
$$('.popup-actions').on('popup:open', function () {
  var randomnumber=Math.floor(Math.random()*500000);
	
	$('#actions_content').load('worker.php?cachebuster='+randomnumber+'&go=getactions', function() {
            
         $('.actionsprogressbar').each(function() { 
            var progress = $$(this).attr('data-progress');
            var progressbar = $$(this);
            myApp.showProgressbar(progressbar, progress, 'red');
            //console.log(progressbar);
         });
         
          
            
         $$(".aloadoutusebutton").click(function() { 
	
          method = "loadoutuse";
          var loadout_id = $$(this).data("loadoutid");
          if (loadout_id > 0) {
            $.ajax({
                url: "worker.php?go="+method+"&id="+loadout_id,
              method: "POST"
              })
            .done(function(data) {
                //console.log('success', data);
                switch(data) {		    		
                  case "success":	    
                    break;
                }
              });
	        }
          });   
            
            
  });
  //console.log('Action Popup opened');
});