/*

  This code is from http://detectmobilebrowsers.mobi/ - please do not republish it without due credit and hyperlink to http://detectmobilebrowsers.mobi/ really, i'd prefer it if it wasn't republished in full as that way it's main source is it's homepage and it's always kept up to date
  
  For help generating the function call visit http://detectmobilebrowsers.mobi/ and use the function generator. If you need serious help with this please drop me an email to andy@andymoore.info with the subject 'DETECTION CODE PAID SUPPORT REUQEST' with a detailed outline of what you need and how I can help and I will get back to you with a proposal for integration.
  
  Published by Andy Moore - .mobi certified mobile web developer - http://andymoore.info/

  This code is free to download and use on non-profit websites, if your website makes a profit or you require support using this code please upgrade.

  Please upgrade for use on commercial websites http://detectmobilebrowsers.mobi/?volume=49999

  To submit a support request please forward your PayPal receipt with your questions to the email address you sent the money to and I will endeavour to get back to you. It might take me a few days but I reply to all support issues with as much helpful info as I can provide. Though really everything is published on the site.

  The function has eight parameters that can be passed to it which define the way it handles different scenarios. These paramaters are:

    * iPhone - Set to true to treat iPhones as mobiles, false to treat them like full browsers or set a URL (including http://) to redirect iPhones and iPods to.
    * Android - Set to true to treat Android handsets as mobiles, false to treat them like full browsers or set a URL (including http://) to redirect Android and Google mobile users to.
    * Opera Mini - Set to true to treat Opera Mini like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Opera Mini users to.
    * Blackberry - Set to true to treat Blackberry like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Blackberry users to.
    * Palm - Set to true to treat Palm OS like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Palm OS users to.
    * Windows - Set to true to treat Windows Mobiles like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Windows Mobile users to.
    * Mobile Redirect URL - This should be full web address (including http://) of the site (or page) you want to send mobile visitors to. Leaving this blank will make the script return true when it detects a mobile.
    * Desktop Redirect URL - This should be full web address (including http://) of the site (or page) you want to send non-mobile visitors to. Leaving this blank will make the script return false when it fails to detect a mobile.

Change Log:

    * 25.11.08 - Added Amazon's Kindle to the pipe seperated array
    * 27.11.08 - Added support for Blackberry options
    * 27.01.09 - Added usage samples & help with PHP in HTML - .zip
    * 09.03.09 - Added support for Windows Mobile options
    * 09.03.09 - Removed 'ppc;'=>'ppc;', from array to reduce false positives
    * 09.03.09 - Added support for Palm OS options
    * 09.03.09 - Added sample .htaccess html.html and help.html files to download
    * 16.03.09 - Edited sample .htaccess file - now works with GoDaddy
    * 14.08.09 - Reduced false positives
    * 14.08.09 - Added Palm Pre
    * 14.08.09 - Added answer about search engine spiders
    * 14.08.09 - Added status variable to report back it's findings for debugging
    * 14.08.09 - Added Torch Mobile Iris Browser to Windows Mobile section
    * 14.08.09 - Added HTC Touch 3G to Windows Mobile section
    * 14.08.09 - Added help links to PHP header and setup PHP in HTML
    * 14.08.09 - Added six usage examples
    * 15.08.09 - Checked against the list of agents in the WURFL - 99.27% detected!
          o 11,489 mobile user agent strings checked
          o 99.27% detection rate after a number of small changes
          o Those user agent strings listed that are not detected are either robots or too generic for user agent detection
          o Any mobiles not detected by their user agent would most likely return true as they'd be detected by the headers they add.
    * 20.11.09 - Removed PDA from the piped array to stop false positives
    * 22.12.09 - Moved the site to a server hosted at Rackspace
    * 23.12.09 - Added support for Mozilla Fennec
    * 23.04.10 - Added support for the Apple iPad
          o Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10
          o Mozilla/5.0 (iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7D11
          o Mozilla/5.0 (iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B317 Safari/531.21.10
    * 23.04.10 - Changed all eregi function calls to user_agent
    * 23.04.10 - Added two more examples
          o Added example-7.php which allows switching between desktop and mobile versions
          o Added example-8.php which shows why the script made the decision it did
    * No longer using include, using require_once instead

bug fixes with many thanks and much credit to http://www.punchkickinteractive.com/ - thanks Ryan!

*/

function mobile_device_detect(iphone, ipad, android, opera, blackberry, palm, windows, mobileredirect, desktopredirect, user_agent, accept){
  var mobile_browser = false; // set mobile browser as false till we can prove otherwise
  var trimmed_user_agent = user_agent.toLowerCase();
  trimmed_user_agent = trimmed_user_agent.substr(0, 4);
  trimmed_user_agent_comp = '1207|3gso|4thp|501i|502i|503i|504i|505i|506i|6310|6590|770s|802s|a wa|acer|acs-|airn|alav|asus|attw|au-m|aur |aus |abac|acoo|aiko|alco|alca|amoi|anex|anny|anyw|aptu|arch|argo|bell|bird|bw-n|bw-u|beck|benq|bilb|blac|c55/|cdm-|chtm|capi|cond|craw|dall|dbte|dc-s|dica|ds-d|ds12|dait|devi|dmob|doco|dopo|el49|erk0|esl8|ez40|ez60|ez70|ezos|ezze|elai|emul|eric|ezwa|fake|fly-|fly_|g-mo|g1 u|g560|gf-5|grun|gene|go.w|good|grad|hcit|hd-m|hd-p|hd-t|hei-|hp i|hpip|hs-c|htc |htc-|htca|htcg|htcp|htcs|htct|htc_|haie|hita|huaw|hutc|i-20|i-go|i-ma|i230|iac|iac-|iac/|ig01|im1k|inno|iris|jata|java|kddi|kgt|kgt/|kpt |kwc-|klon|lexi|lg g|lg-a|lg-b|lg-c|lg-d|lg-f|lg-g|lg-k|lg-l|lg-m|lg-o|lg-p|lg-s|lg-t|lg-u|lg-w|lg/k|lg/l|lg/u|lg50|lg54|lge-|lge/|lynx|leno|m1-w|m3ga|m50/|maui|mc01|mc21|mcca|medi|meri|mio8|mioa|mo01|mo02|mode|modo|mot |mot-|mt50|mtp1|mtv |mate|maxo|merc|mits|mobi|motv|mozz|n100|n101|n102|n202|n203|n300|n302|n500|n502|n505|n700|n701|n710|nec-|nem-|newg|neon|netf|noki|nzph|o2 x|o2-x|opwv|owg1|opti|oran|p800|pand|pg-1|pg-2|pg-3|pg-6|pg-8|pg-c|pg13|phil|pn-2|pt-g|palm|pana|pire|pock|pose|psio|qa-a|qc-2|qc-3|qc-5|qc-7|qc07|qc12|qc21|qc32|qc60|qci-|qwap|qtek|r380|r600|raks|rim9|rove|s55/|sage|sams|sc01|sch-|scp-|sdk/|se47|sec-|sec0|sec1|semc|sgh-|shar|sie-|sk-0|sl45|slid|smb3|smt5|sp01|sph-|spv |spv-|sy01|samm|sany|sava|scoo|send|siem|smar|smit|soft|sony|t-mo|t218|t250|t600|t610|t618|tcl-|tdg-|telm|tim-|ts70|tsm-|tsm3|tsm5|tx-9|tagt|talk|teli|topl|hiba|up.b|upg1|utst|v400|v750|veri|vk-v|vk40|vk50|vk52|vk53|vm40|vx98|virg|vite|voda|vulc|w3c |w3c-|wapj|wapp|wapu|wapm|wig |wapi|wapr|wapv|wapy|wapa|waps|wapt|winc|winw|wonu|x700|xda2|xdag|yas-|your|zte-|zeto|acs-|alav|alca|amoi|aste|audi|avan|benq|bird|blac|blaz|brew|brvw|bumb|ccwa|cell|cldc|cmd-|dang|doco|eml2|eric|fetc|hipt|http|ibro|idea|ikom|inno|ipaq|jbro|jemu|java|jigs|kddi|keji|kyoc|kyok|leno|lg-c|lg-d|lg-g|lge-|libw|m-cr|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|mywa|nec-|newt|nok6|noki|o2im|opwv|palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|rozo|sage|sama|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|treo|tsm-|upg1|upsi|vk-v|voda|vx52|vx53|vx60|vx61|vx70|vx80|vx81|vx83|vx85|wap-|wapa|wapi|wapp|wapr|webc|whit|winw|wmlb|xda-';

  user_agent_comp = new RegExp("(mini 9.5|vx1000|lge |m800|e860|u940|ux840|compal|wireless| mobi|ahong|lg380|lgku|lgu900|lg210|lg47|lg920|lg840|lg370|sam-r|mg50|s55|g83|t66|vx400|mk99|d615|d763|el370|sl900|mp500|samu3|samu4|vx10|xda_|samu5|samu6|samu7|samu9|a615|b832|m881|s920|n210|s700|c-810|_h797|mob-x|sk16d|848b|mowser|s580|r800|471x|v120|rim8|c500foma:|160x|x160|480x|x640|t503|w839|i250|sprint|w398samr810|m5252|c7100|mt126|x225|s5330|s820|htil-g1|fly v71|s302|-x113|novarra|k610i|-three|8325rc|8352rc|sanyo|vx54|c888|nx250|n120|mtk |c5588|s710|t880|c5005|i;458x|p404i|s210|c5100|teleca|s940|c500|s590|foma|samsu|vx8|vx9|a1000|_mms|myx|a700|gu1100|bc831|e300|ems100|me701|me702m-three|sd588|s800|8325rc|ac831|mw200|brew |d88|htc\/|htc_touch|355x|m50|km100|d736|p-9521|telco|sl74|ktouch|m4u\/|me702|8325rc|kddi|phone|lg |sonyericsson|samsung|240x|x320|vx10|nokia|sony cmd|motorola|up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|pocket|kindle|mobile|psp|treo)", "gi");

  switch(true){ // using a switch against the following statements which could return true is more efficient than the previous method of using if statements

    case (user_agent.search(/ipad/gi) > -1): // we find the word ipad in the user agent
      mobile_browser = (ipad == false) ? false : true; // mobile browser is either true or false depending on the setting of ipad when calling the function
      status = 'Apple iPad';
      if(ipad != true && ipad != false)
      {
        if(ipad.substr(0, 4)=='http'){ // does the value of ipad resemble a url
          mobileredirect = ipad; // set the mobile redirect url to the url value stored in the ipad value
        } // ends the if for ipad being a url
      }
    break; // break out and skip the rest if we've had a match on the ipad // this goes before the iphone to catch it else it would return on the iphone instead

    case (user_agent.search(/ipod/gi) > -1 || user_agent.search(/iphone/gi) > -1): // we find the words iphone or ipod in the user agent
      mobile_browser = (iphone == false) ? false : true; // mobile browser is either true or false depending on the setting of iphone when calling the function
      status = 'Apple';
      if(iphone != true && iphone != false)
      {
        if(iphone.substr(0, 4)=='http'){ // does the value of iphone resemble a url
        mobileredirect = iphone; // set the mobile redirect url to the url value stored in the iphone value
        } // ends the if for iphone being a url
      }
    break; // break out and skip the rest if we've had a match on the iphone or ipod

    case (user_agent.search(/android/gi) > -1):  // we find android in the user agent
      mobile_browser = (android == false) ? false : true; // mobile browser is either true or false depending on the setting of android when calling the function
      status = 'Android';
      if(android != true && android != false)
      {
        if(android.substr(0, 4)=='http'){ // does the value of android resemble a url
        mobileredirect = android; // set the mobile redirect url to the url value stored in the android value
        } // ends the if for android being a url
      }
    break; // break out and skip the rest if we've had a match on android

    case (user_agent.search(/opera mini/gi) > -1): // we find opera mini in the user agent
      mobile_browser = (opera == false) ? false : true; // mobile browser is either true or false depending on the setting of opera when calling the function
      status = 'Opera';
      if(opera != true && opera != false)
      {
        if(opera.substr(0, 4)=='http'){ // does the value of opera resemble a rul
        mobileredirect = opera; // set the mobile redirect url to the url value stored in the opera value
        } // ends the if for opera being a url
      }
    break; // break out and skip the rest if we've had a match on opera

    case (user_agent.search(/blackberry/gi) > -1): // we find blackberry in the user agent
      mobile_browser = (blackberry == false) ? false : true; // mobile browser is either true or false depending on the setting of blackberry when calling the function
      status = 'Blackberry';
      if(blackberry != true && blackberry != false)
      {
        if(blackberry.substr(0, 4)=='http'){ // does the value of blackberry resemble a rul
        mobileredirect = blackberry; // set the mobile redirect url to the url value stored in the blackberry value
        } // ends the if for blackberry being a url
      }
    break; // break out and skip the rest if we've had a match on blackberry

    case (user_agent.search(/(pre\/|palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/gi) > -1): // we find palm os in the user agent - the i at the end makes it case insensitive
      mobile_browser = (palm == false) ? false : true; // mobile browser is either true or false depending on the setting of palm when calling the function
      status = 'Palm';
      if(palm != true && palm != false)
      {
        if(palm.substr(0, 4)=='http'){ // does the value of palm resemble a rul
        mobileredirect = palm; // set the mobile redirect url to the url value stored in the palm value
        } // ends the if for palm being a url
      }
    break; // break out and skip the rest if we've had a match on palm os

    case (user_agent.search(/(iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile)/gi) > -1): // we find windows mobile in the user agent - the i at the end makes it case insensitive
      mobile_browser = (windows == false) ? false : true; // mobile browser is either true or false depending on the setting of windows when calling the function
      status = 'Windows Smartphone';
      if(windows != true && windows != false)
      {
        if(windows.substr(0, 4)=='http'){ // does the value of windows resemble a rul
        mobileredirect = windows; // set the mobile redirect url to the url value stored in the windows value
        } // ends the if for windows being a url
      }
    break; // break out and skip the rest if we've had a match on windows

    case (user_agent.search(user_agent_comp) > -1): // check if any of the values listed create a match on the user agent - these are some of the most common terms used in agents to identify them as being mobile devices - the i at the end makes it case insensitive
      mobile_browser = true; // set mobile browser to true
      status = 'Mobile matched on piped user_agent';
    break; // break out and skip the rest if we've user_agent on the user agent returned true 

    case ((accept.indexOf('text/vnd.wap.wml') > -1) || (accept.indexOf('application/vnd.wap.xhtml+xml') > -1)): // is the device showing signs of support for text/vnd.wap.wml or application/vnd.wap.xhtml+xml
      mobile_browser = true; // set mobile browser to true
      status = 'Mobile matched on content accept header';
    break; // break out and skip the rest if we've had a match on the content accept headers
/*
    case profileheaderisset: // is the device giving us a HTTP_X_WAP_PROFILE or HTTP_PROFILE header - only mobile devices would do this
      mobile_browser = true; // set mobile browser to true
      status = 'Mobile matched on profile headers being set';
    break; // break out and skip the final step if we've had a return true on the mobile specfic headers
*/
    case (trimmed_user_agent_comp.indexOf(trimmed_user_agent) > -1): // check against a list of trimmed user agents to see if we find a match
      mobile_browser = true; // set mobile browser to true
      status = 'Mobile matched on in_array';
    break; // break even though it's the last statement in the switch so there's nothing to break away from but it seems better to include it than exclude it

    default:
      mobile_browser = false; // set mobile browser to false
      status = 'Desktop / full capability browser';
    break; // break even though it's the last statement in the switch so there's nothing to break away from but it seems better to include it than exclude it

  } // ends the switch 

  // tell adaptation services (transcoders and proxies) to not alter the content based on user agent as it's already being managed by this script, some of them suck though and will disregard this....
	// header('Cache-Control: no-transform'); // http://mobiforge.com/developing/story/setting-http-headers-advise-transcoding-proxies
	// header('Vary: User-Agent, Accept'); // http://mobiforge.com/developing/story/setting-http-headers-advise-transcoding-proxies

  // if redirect (either the value of the mobile or desktop redirect depending on the value of mobile_browser) is true redirect else we return the status of mobile_browser
  if(redirect = (mobile_browser == true) ? mobileredirect : desktopredirect){
    window.location = redirect; // redirect to the right url for this device
  }else{ 
		// a couple of folkas have asked about the status - that's there to help you debug and understand what the script is doing
		return new Array(mobile_browser, status); // is a mobile so we are returning an array ['0'] is true ['1'] is the status value
	}

} // ends function mobile_device_detect
