// this is for IE fixed....
ie = false;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
 var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
 if (ieversion>=5){
  ie = true;
 }
 //  alert("You're using IE8 or above");
 // else if (ieversion>=7)
 //  alert("You're using IE7.x");
 // else if (ieversion>=6)
 //  alert("You're using IE6.x");
 // else if (ieversion>=5)
 //  alert("You're using IE5.x");
}
if (!window.console || !console || ie){
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
        "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile",
        "profileEnd"];
  window.console = {};
  for (var i = 0; i < names.length; ++i){
      window.console[names[i]] = function() {};
  }
}

// try this later
// var isIE = function() {
//     var ie, ieversion;
//     ie = false;
//     if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
//       ieversion = new Number(RegExp.$1);
//       if (ieversion >= 5) {
//         ie = true;
//       }
//     }
//     return ie;
//   };
//
// var consoleFix = function() {
//   var name, names, _i, _len, _results;
//   if (!window.console || !console || !isIE) {
//     names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group",
// 			 "groupEnd", "time",
// 			 "timeEnd", "count", "trace", "profile", "profileEnd"];
//     window.console = {};
//     _results = [];
//     for (_i = 0, _len = names.length; _i < _len; _i++) {
//       name = names[_i];
//       _results.push(window.console[name] = function() {});
//     }
//     return _results;
//   }
// };
//
// consoleFix();

// facebook social plugin related
$(function(){
  $('body').ajaxError(function(e, xhr, settings, exception) {
    console.error('ajaxError', e, xhr, settings, exception, xhr.status);
    // Override of RestGraph::RailsUtil method to pass back (instead of the
    // standard HTTP redirect) a special JSON encoded redirect using
    // custom HTTP status code 310. This is to get around the fact that the
    // built-in browser Ajax redirect will not follow to another
    // domain (i.e. www.facebook.com).
    if (xhr.status == 310) {
      var parsed = $.parseJSON(xhr.responseText);
      if (parsed.redirect_to) {
        window.location = parsed.redirect_to;    // Navigate full browser there!
      }
    } else if (xhr.status == 311){
      window.location.reload();
    }
  });}
);

fbLogout = function(redirect_url){
  FB.logout(function(response){
	  if (typeof redirect_url != 'undefined'){
	    redirectTo(redirect_url);
	  }else{
      window.location.reload();
  	  }
  });
};

fbLogin = function(){
  FB.login(function(response){
		if (response.authResponse) {
			// User is connected to the application.
		  //var accessToken = response.authResponse.accessToken;
			// window.location.reload();
		} else {
			//user cancelled login
		}
  });
};

send_apprequest = function(title, message){
	FB.ui({ method: 'apprequests',
			title: title,
      		message: message
		},
		function(response) {
			console.debug(response);
	   }
	);
}

show = function(_ids){
  var ids = _ids.split(',');
  var str = $.map(ids, function(id){ return '#' + id; }).join(',');
  $(str).show();
};

hide = function(_ids){
  var ids = _ids.split(',');
  var str = $.map(ids, function(id){ return '#' + id; }).join(',');
  $(str).hide();
};

_clickrewrite = function(url, response_id, hide_id, show_id, callback) {
  if (hide_id) hide(hide_id);
  if (show_id) show(show_id);

  $.ajax({
    type: "POST",
    url: url,
    success: function(data){
      if (hide_id) show(hide_id);
      if (show_id) hide(show_id);
      console.debug('ajax done');
      //console.debug(data);
      var target_id = '#'+response_id;
      $(target_id).html(data);
      if (typeof callback == 'function') callback();
    }
  });
};

_clickreplace = function(url, selector, callback){
  $.ajax({
    type: "POST",
    url: url,
    success: function(data){
	  $(selector).replaceWith(data);
      if (typeof callback == 'function') callback();
    }
  });
}

redirectTo = function(url){
  window.location.href=url;
};

// this for clear or show default input text
clearInputText = function(field){
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value === ''        ||
             field.value === undefined ||
             field.value === null) field.value = field.defaultValue;
};

stringBytes = function(str){
	if (typeof str === undefined){
		return 0;
	}else{
		var arr = str.match(/[^\x00-\xff]/ig);
		return arr === null ? str.length : str.length + arr.length;
	}
};

// this function returns an utf-8 string which has the maximum
// [bytes], it would truncate it if it's too long.
slice_utf8 = function(str, max_bytes){
  var result = ''
  for(var byte_size=0, i=0; i<str.length; ++i){
    var     codepoint = str.charCodeAt(i),
                                  char_bytes = 0;
    if(     codepoint <   0x007F) char_bytes = 1;
    else if(codepoint <   0x07FF) char_bytes = 2;
    else if(codepoint <   0xFFFF) char_bytes = 3;
    else if(codepoint < 0x10FFFF) char_bytes = 4;
    else                          char_bytes = 5;

    if(byte_size + char_bytes <= max_bytes){
      result    += str[i];
      byte_size += char_bytes;
    }
    else{
      break;
    }
  }
  return result;
};

$(function(){
	$('.spinner_button').live('click', function(){
	  var button_id = this.id;
	  show(button_id+'_spinner');
	  hide(button_id+'_text');
	});

	// for button form_css_button
	$("form.form_css_button").submit(function(e){
		e.preventDefault();
		var form = $(this);
		if (form.attr('spinner')){
			form.addClass('loading');
		}
		$.post(form.attr('action'), {}, function(data){
			if (form.attr('spinner')){
				form.removeClass('loading');
			}
		});
	});

	// Function to get the Max value in Array
	Array.max = function( array ){
	    return Math.max.apply( Math, array );
	};

	// Function to get the Min value in Array
	Array.min = function( array ){
	   return Math.min.apply( Math, array );
	};
});

// preload images from the css file
// have some problem in different browser
// $.preloadCssImages = function(){
//   var allImgs = [];//new array for all the image urls
//   var k = 0; //iterator for adding images
//   var sheets = document.styleSheets;//array of stylesheets
//
//   for(var i = 0; i<sheets .length; i++){//loop through each stylesheet
//     var cssPile = '';//create large string of all css rules in sheet
//     var csshref = (sheets[i].href) ? sheets[i].href : 'window.location.href';
//     var baseURLarr = csshref.split('/');//split href at / to make array
//     baseURLarr.pop();//remove file path from baseURL array
//     var baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
//     if(baseURL !== "") baseURL += '/'; //tack on a / if needed
//     if(document.styleSheets[i].cssRules){//w3
//       var thisSheetRules = document.styleSheets[i].cssRules; //w3
//       for(var j = 0; j<thisSheetRules.length; j++){
//         cssPile+= thisSheetRules[j].cssText;
//       }
//     }
//     else {
//       cssPile+= document.styleSheets[i].cssText;
//     }
//     //parse cssPile for image urls and load them into the DOM
//     var imgUrls = cssPile.match(/url\((.+?\.(gif|jpg|jpeg|png))\s*\)/g);//reg ex to get a string of between a "(" and a ".filename"
//     if(imgUrls !== null && imgUrls.length>0 && imgUrls !== ''){//loop array
//       var arr = jQuery.makeArray(imgUrls);//create array from regex obj
//       jQuery(arr).each(function(){
//         this.match(/url\((.+?\.(gif|jpg|jpeg|png))\s*\)/g);
//         url = RegExp.$1;
//         allImgs[k] = new Image(); //new img obj
//         allImgs[k].src = (url[0] == '/' || url.match('http://')) ? url : baseURL + url;     //set src either absolute or rel to css dir
//         k++;
//       });
//     }
//   }//loop
//   return allImgs;
// };

var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function(picturesArray) {
  var args_len = picturesArray.length;
  for (var i = args_len; i--;) {
    var cacheImage = document.createElement('img');
    cacheImage.src = picturesArray[i];
    cache.push(cacheImage);
  }
};

// from http://jsfiddle.net/sxGtM/3/
// to serialize form data to json normal format
// { name1 : value1, name2 : value2 }
$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};



var CBYoutube = {
	DEFAULTS_OPTIONS: {
		width : '100%',
		height : '270',
		frameborder : '0',
		url_params : {
			autoplay : '1'
		}
	},
	play : function(vuid, selector, options){
		options = $.extend({}, CBYoutube.DEFAULTS_OPTIONS, options || {});
		options['src'] = 'http://www.youtube.com/embed/'+vuid+'?'+$.param(options['url_params']);
		$(selector).parent().html(
			$('<iframe>').attr(options)
		)
	}
}
