var originBgW = 1136;
var originBgH = 640;
var globalScale = 1;
var globalOffset = 0;
var screenStatus = 1;

var btns;

var red_light;
var red_light_img_path_on = "./img/light_red_on.png";
var red_light_img_path_off = "./img/light_red_off.png";
var green_light;
var green_light_img_path_on = "./img/light_green_on.png";
var green_light_img_path_off = "./img/light_green_off.png";

var pad_left;
var pad_right;


var isRunning = true;
//Free or Full app
var isFullMode = false;
//Test mode will use default Ad
var isTestMode = false;

var myOS = "FxOS";
var webSiteLink = "http://www.omega.url.tw";
var facebookPageLink = "https://facebook.com/omegastudiopage";
var moreAppsLink = "https://marketplace.firefox.com/search?q=omega+studio";
var fullVerLink = "https://marketplace.firefox.com/app/finger-timer-full";
var freeVerLink = "https://marketplace.firefox.com/app/finger-timer";
var adLink = "http://www.omega.url.tw/_adhtml/finger_timer_fxos.html";
var rateThisAppLink;

var screenlock;

var shareObjName = "FingerTimerFree";
if(isFullMode){
  shareObjName = "FingerTimerFull";
}

rateThisAppLink = freeVerLink;
if(isFullMode){
  rateThisAppLink = fullVerLink;
}

var TIME_LIMIT = 10 * 60 * 1000 - 1;
if(isFullMode){
  TIME_LIMIT = 60 * 60 * 1000 - 1;
}
var TIMER_IDLE = 1;
var TIMER_PRESS_HOLD = 2;
var TIMER_READY_TO_START = 3;
var TIMER_RUNNING = 4;
var TIMER_RESULT = 5;
var timerStatus;

///

var startTime;
var timerTime;

var myPressTimer = 0;
var myLightTimer = 0;

var my_scramble_cube_size = 3;
var my_scramble_cube_size_max = 5;
if(!isFullMode){
  my_scramble_cube_size_max = 3;
}

//1: none
//full ver: 2-5
//free ver: 2-3

function myBtn(imgId, imgPath0, imgPath1, btnAction){
  this.imgId = imgId;
  this.imgPath0 = imgPath0;
  this.imgPath1 = imgPath1;
  this.btnAction = btnAction;
  this.isDown = false;
  this.isInside = false;

  this.imgObj = document.getElementById(this.imgId);
  this.imgObj.myParent = this;
  this.imgObj.onmousedown = function(event){
    event.preventDefault();
    this.myParent.myDown(event);
  };
  this.imgObj.ontouchstart = function(event){
    event.preventDefault();
    this.myParent.myDown(event);
  };
  this.myDown = function(event){
    this.isDown = true;
    this.isInside = true;
    this.changeStatus(1);
  };
  this.imgObj.onmouseup = function(event){
    event.preventDefault();
    this.myParent.myUp(event);
  };
  this.imgObj.ontouchend = function(event){
    event.preventDefault();
    this.myParent.myUp(event);
  };
  this.myUp = function(event){
    if(this.isDown && this.isInside){
      this.isDown = false;
      this.changeStatus(0);
      this.btnAction();
    }
  };
  
  this.imgObj.ontouchmove = function(event){
    event.preventDefault();
    var oldIsInside = this.isInside;
    var tX = event.changedTouches[0].clientX / globalScale;
    var tY = event.changedTouches[0].clientY / globalScale;
    this.isInside = (tX > this.offsetLeft  &&
                     tX < this.offsetLeft + this.offsetWidth &&
                     tY > this.offsetTop &&
                     tY < this.offsetTop + this.offsetHeight
                    );
    //myTrace(oldIsInside + " " + this.isInside);

    if(!this.isInside){
      this.myParent.myOut(event);
    }else{
      this.myParent.myEnter(event);
    }
    /*
    if(oldIsInside && !this.isInside){
      this.myParent.myOut(event);
    }else if((!oldIsInside) && this.isInside){
      this.myParent.myEnter(event);
    }
    */
    /*
    myTrace(parseInt(event.changedTouches[0].clientX / globalScale) + " " +
      parseInt(this.offsetLeft) + " " +
      parseInt(this.offsetWidth)
      );
    */
  };

  this.imgObj.onmouseout = function(event){
    event.preventDefault();
    this.myParent.myOut(event);
  };
  /* this doesn't work
  this.imgObj.ontouchleave = function(event){
    event.preventDefault();
    this.myParent.myOut(event);
  };
  */
  this.myOut = function(event){
    this.isInside = false;
    this.changeStatus(0);
  };
  
  this.imgObj.onmouseenter = function(event){
    event.preventDefault();
    this.myParent.myEnter(event);
  };
  /* this doesn't work
  this.imgObj.ontouchleave = function(event){
    event.preventDefault();
    this.myParent.myOut(event);
  };
  */
  this.myEnter = function(event){
    if(this.isDown){
      this.isInside = true;
      this.changeStatus(1);
    }
  };

  this.myUpOutside = function(event){
    this.isDown = false;
    this.isInside = false;
    this.changeStatus(0);
  };

  this.isMe = function(aImgId){
    return (this.imgId == aImgId);
  };
  this.changeStatus = function(aStatusIdx){
    switch(aStatusIdx){
      case 0:
        this.imgObj.src = this.imgPath0;
        break;
      case 1:
        this.imgObj.src = this.imgPath1;
        break;
      default:
        break;
    }
  };
}

document.onmousedown = function(event){
  event.preventDefault();
  myDown(event);
};

document.ontouchstart = function(event){
  event.preventDefault();
  myDown(event);
  //addTouchPnt(event);
  touchChanged(event);
};

function myDown(event){
  //if(screenStatus==2){//about
  if(event.target.id == "aboutWebSiteTF"){
    onClickWebSiteLink();
  }else if(event.target.id == "aboutFacebookPageTF"){
    onClickFacebookPageLink();
  }else if(event.target.id == "aboutMoreAppsTF"){
    onClickMoreAppsLink();
  }else if(event.target.id == "aboutRateThisAppTF"){
    onClickRateThisAppLink();
  }else if(event.target.id == "aboutGetFullVerTF"){
    onClickFullVerLink();
  }
}

document.onmouseup = function(event){
  event.preventDefault();
  myUp(event);
};

document.ontouchend = function(event){
  event.preventDefault();
  myUp(event);
  //removeTouchPnt(event);
  touchChanged(event);
};

function myUp(event){

  for(var i=0;i<btns.length;i++){
    if(!btns[i].isMe(event.target.id)){
      btns[i].myUpOutside(event);
    }
  }

}


document.ontouchmove = function(event){
  event.preventDefault();

  //addTouchPnt(event);
  touchChanged(event);
};

function rescaleLayout(){
  var tH = originBgH;
  var tDeviceH = (window.innerHeight > 0) ? window.innerHeight : screen.height;
  var tScale = tDeviceH / tH;
  globalScale = tScale;
  //alert(tScale);
  var tStr = "scale(" +tScale+ ")";
  document.body.style.transform = tStr;
  document.body.style.msTransform = tStr;
  document.body.style.MozTransform = tStr;
  document.body.style.webkitTransform = tStr;

  var tW = originBgW;
  var tDeviceW = (window.innerWidth > 0) ? window.innerWidth : screen.width;
  var tScaledDeviceW = tDeviceW / tScale;
  var tOffset = (tW - tScaledDeviceW) / 2;
  globalOffset = tOffset;
  tOffset = tOffset > 0 ? tOffset : 0;
  //var tMargin = tOffset + 43;
  document.getElementById("padicon1").style.left = (tOffset + 43) + "px";
  document.getElementById("padicon2").style.right = (tOffset + 43) + "px";

  document.getElementById("about_close_btn").style.right = tOffset + "px";

  document.getElementById("wrapper0").style.clip = "rect(0px," + (tScaledDeviceW+tOffset) + "px," + originBgH + "px,"+ tOffset + "px)";
}

function aboutBtnAction(){
  screenStatus = 2;
  document.getElementById("wrapper").style.top="0px";
  //myTrace("aboutBtnAction");
}
function resetBtnAction(){
  //myTrace("resetBtnAction");

  //BUG!!!!//
  //rescaleLayout();

  doReset();
  //updateScrambleString(my_scramble_cube_size);
  //reloadAd();
}
function aboutCloseBtnAction(){
  screenStatus = 1;
  document.getElementById("wrapper").style.top= -originBgH + "px";
  //myTrace("aboutCloseBtnAction");
}
/*
function aboutCubeSizeBtnAction(){
    my_scramble_cube_size++;
    if(my_scramble_cube_size>my_scramble_cube_size_max){
      my_scramble_cube_size = 1;
    }
    base_mc.cube_size_btn_mc.gotoAndStop(my_scramble_cube_size);
    updateScrambleString(my_scramble_cube_size);
    saveData();
}
*/

function onClickWebSiteLink () {
  var openURL = new MozActivity({
    name: "view",
    data: {
      type: "url", 
      url: webSiteLink
    }
  });
}
function onClickFacebookPageLink () {
  var openURL = new MozActivity({
    name: "view",
    data: {
      type: "url", 
      url: facebookPageLink
    }
  });
}
function onClickMoreAppsLink () {
  var openURL = new MozActivity({
    name: "view",
    data: {
      type: "url", 
      url: moreAppsLink
    }
  });
}
function onClickRateThisAppLink () {
  var openURL = new MozActivity({
    name: "view",
    data: {
      type: "url", 
      url: rateThisAppLink
    }
  });
}
function onClickFullVerLink () {
  var openURL = new MozActivity({
    name: "view",
    data: {
      type: "url", 
      url: fullVerLink
    }
  });
}

function touchChanged(e){

  if(screenStatus==1){//main

    var tStr="";
    var tTouches = e.touches;
    var left_is_touched = false;
    var right_is_touched = false;

    for(var i=0;i<tTouches.length;i++){
      
      var tX = tTouches[i].clientX / globalScale + globalOffset;
      var tY = tTouches[i].clientY / globalScale;
      if(!left_is_touched){
        left_is_touched = (tX > pad_left.offsetLeft  &&
                           tX < pad_left.offsetLeft + pad_left.offsetWidth &&
                           tY > pad_left.offsetTop &&
                           tY < pad_left.offsetTop + pad_left.offsetHeight
                           );
      }
      if(!right_is_touched){
        right_is_touched = (tX > pad_right.offsetLeft  &&
                            tX < pad_right.offsetLeft + pad_right.offsetWidth &&
                            tY > pad_right.offsetTop &&
                            tY < pad_right.offsetTop + pad_right.offsetHeight
                            );
      }
      //tStr += tTouches[i].clientX + ", " + tTouches[i].clientY + "; " + pad_left.offsetLeft + ", " + pad_left.offsetLeft + pad_left.offsetWidth + "<br>";

      //tStr += tX + "; " + pad_left.offsetLeft + ", " + (pad_left.offsetLeft + pad_left.offsetWidth) + "<br>";
    
    
    }
    //myTrace(tStr);
    myTrigger(left_is_touched && right_is_touched);
    //myTrigger(touch_left_ary.length>0 && touch_right_ary.length>0);
  }
}

function myTrigger(isBothTouched){
  if(timerStatus == TIMER_IDLE){
    if(isBothTouched){
      myPressTimer = 0;
      timerStatus = TIMER_PRESS_HOLD;
      showLight(true, false);
    }
  }else if(timerStatus == TIMER_PRESS_HOLD){
    if(!isBothTouched){
      timerStatus = TIMER_IDLE;
      showLight(false, false);
    }
  }else if(timerStatus == TIMER_READY_TO_START){
    if(!isBothTouched){
      doStart();
    }
  }else if(timerStatus == TIMER_RUNNING){
    if(isBothTouched){
      doStop();
    }
  }else if(timerStatus == TIMER_RESULT){
    if(isBothTouched){
      showLight(true, false);
    }else{
      showLight(false, false);
    }
  }
}

document.onkeydown = function(event) {
  //myTrace(event.keyCode);
  if (event.keyCode == 32) {
    myTrigger(true);
  }
}

document.onkeyup = function(event) {
  if (event.keyCode == 32) {
    myTrigger(false);
  }
}

function showLight(redOn, greenOn){
  //myTrace((redOn?"on":"off") + " " + (greenOn?"on":"off"));
  if(redOn){
    red_light.src = red_light_img_path_on;
  }else{
    red_light.src = red_light_img_path_off;
  }
  if(greenOn){
    green_light.src = green_light_img_path_on;
  }else{
    green_light.src = green_light_img_path_off;
  }
}

function updateDigits(aTime){
  
  var minutes = Math.floor(Math.floor(aTime/1000)/60);
  var seconds = Math.floor(aTime/1000) % 60;
  var miseconds = Math.floor(aTime/10) % 100;
  var min = (minutes<1)?"  ":(minutes+":");
  var secondsZero = (seconds<10)?" ":"";
  var misecondsZero = (miseconds<10)?"0":"";
  document.getElementById("time").innerHTML = min+secondsZero+seconds+"."+misecondsZero+miseconds;
  //document.getElementById("time").innerHTML = ""+aTime;
  //trace(min+":"+secondsZero+seconds+":"+misecondsZero+miseconds);
}

function doStart(){
  if(timerStatus == TIMER_IDLE || timerStatus == TIMER_READY_TO_START){
    startTime = (new Date()).getTime();
    timerStatus = TIMER_RUNNING;
    myLightTimer = 0;

    try {
      screenlock = window.navigator.requestWakeLock('screen');
    }catch (e) {
      //
    }
  
    // Dimming
    //NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
  }
}

function doStop(){
  if(timerStatus == TIMER_RUNNING){
    timerStatus = TIMER_RESULT;
    showLight(true, false);
    
    try {
      screenlock.unlock();
    }catch (e) {
      //
    }
    // Dimming
    //NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.NORMAL;
  }
}

function doReset(){
  timerStatus = TIMER_IDLE;
  showLight(false, false);
  timerTime = 0;
  updateDigits(timerTime);
  
    try {
      screenlock.unlock();
    }catch (e) {
      //
    }
  // Dimming
  //NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.NORMAL;
}

function myEnterFrame(){
  
  if(isRunning){ // && !baseMCisMoving){
    if(timerStatus == TIMER_RUNNING){
      timerTime = (new Date()).getTime() - startTime;
      
      if(timerTime<TIME_LIMIT){
        updateDigits(timerTime);
        
          myLightTimer++;
          if(myLightTimer==2){
            showLight(true, false);
          }else if(myLightTimer==4){
            showLight(false, true);
            myLightTimer=0;
          }
        
      }else{
        doReset();
      }
      
      
    }else if(timerStatus == TIMER_PRESS_HOLD){
      if(myPressTimer<30){
        myPressTimer++;
      }else{
        timerStatus = TIMER_READY_TO_START;
        showLight(true, true);
      }
    }
  }
}

//init
document.addEventListener('DOMContentLoaded', function () {

  //init
  red_light = document.getElementById("red_light");
  green_light = document.getElementById("green_light");
  pad_left = document.getElementById("pad_left");
  pad_right = document.getElementById("pad_right");
  timerStatus = TIMER_IDLE;
  showLight(false, false);
  timerTime = 0;

  btns = [
    new myBtn("about_btn", "./img/button_about_n.png", "./img/button_about_p.png", aboutBtnAction),
    new myBtn("reset_btn", "./img/button_reset_n.png", "./img/button_reset_p.png", resetBtnAction),
    new myBtn("about_close_btn", "./img/about_btn_close_n.png", "./img/about_btn_close_p.png", aboutCloseBtnAction)
  ];

  rescaleLayout();

  window.onresize = function(event) {
      rescaleLayout();
  };

  if(isFullMode){
    TIME_LIMIT = 60 * 60 * 1000 - 1;
    document.getElementById("timeshadow").innerHTML = "88:88.88";

    document.getElementById("aboutTitleTF").innerHTML = "Finger Timer Full";
    document.getElementById("aboutGetFullVerTF").style.visibility = "hidden";
  }else{
    document.getElementById("timeshadow").innerHTML = "8:88.88";

    document.getElementById("aboutTitleTF").innerHTML = "Finger Timer";
    //for 1.0.0, hide "get full ver link" also
    document.getElementById("aboutGetFullVerTF").style.visibility = "hidden";
  }

  var myFrameObj=setInterval(myEnterFrame,33);
});

function myTrace(aStr){
  document.getElementById("myTrace").innerHTML = aStr;
}

//////////////////////////////
//action script///////////////
//////////////////////////////

////
/*
NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, handleDeactivate, false, 0, true);
NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, handleActivate, false, 0, true);

function handleDeactivate(e:Event) {
  
  base_mc.displaylink_bubble_mc.disallowConnection();
  //saveData();
  isRunning = false;
  
}
function handleActivate(e:Event) {
  isRunning = true;
}

///////////////////////////
//  AD  //
///////////////////////////

var webView:StageWebView;
var isFocusInAd:Boolean = false;

function onLocationChanging( e:LocationChangeEvent ):void {
  if(isFocusInAd){
    e.preventDefault(); 
    navigateToURL( new URLRequest( e.location ) ); 
  }
}

function onMyFocusIn( e:FocusEvent ):void {
  trace("focus in");
  isFocusInAd = true;
}
function onMyFocusOut( e:FocusEvent ):void {
  trace("focus out");
  isFocusInAd = false;
}

function setAdVisibility(aVisibility:Boolean){
  if(!isFullMode){
    if(aVisibility){
      webView.viewPort = new Rectangle( (stage.stageWidth-320*2)/2 , (stage.stageHeight - myScaledFSH)/2 , 320*2, 50*2);
    }else{
      webView.viewPort = new Rectangle( -1000, -1000 , 320*2, 50*2);
    }
  }
}

var adTimerDelay:Number = 5000;

function reloadAd(){
  if(!isFullMode && !isTestMode){
    webView.loadURL( adLink );
  }
}

if(!isFullMode && !isTestMode){
  
  webView = new StageWebView(); 
  
  setAdVisibility(true);
  webView.stage = this.stage;

  webView.addEventListener( LocationChangeEvent.LOCATION_CHANGING, onLocationChanging ); 
  webView.addEventListener( FocusEvent.FOCUS_IN, onMyFocusIn ); 
  webView.addEventListener( FocusEvent.FOCUS_OUT, onMyFocusOut ); 
  webView.loadURL( adLink ); 
  
}
*/

/////////////////////////

///////Save and Load data

/*
function saveData(){
  // Get the shared object.
  var so:SharedObject = SharedObject.getLocal(shareObjName);

  // Update the age variable.
  so.data["my_scramble_cube_size"] = my_scramble_cube_size;
  // And flush our changes.
  so.flush();
}
 
function loadData(){
  // Get the shared object.
  var so:SharedObject = SharedObject.getLocal(shareObjName);
  
  // And indicate the value for debugging.
  //trace(so.data["hiScore"]);
  
  my_scramble_cube_size = so.data["my_scramble_cube_size"];
  if(my_scramble_cube_size == undefined || my_scramble_cube_size == null){
    my_scramble_cube_size = 3;
  }
}

///////

loadData();

base_mc.cube_size_btn_mc.gotoAndStop(my_scramble_cube_size);
updateScrambleString(my_scramble_cube_size);
*/
////
