Youtube Api JSON arranges results incorrectly - json

I'm using the Video Picker app (by LockeVN: https://github.com/lockevn/YouTube-video-picker), and the results i'm getting are not ordered like they are on the youtube website (or any other search app on github).
FOR EXAMPLE:
I type in : 'Bizarre Inc feat Angie Brown I'm Gonna Get You'.
The first video I get in youtube is: 'Bizarre Inc feat Angie Brown - I'm Gonna Get You (1992)'.
The first video I get in Video Picker app is:'BIZARRE INC - I'M GONNA GET YOU (SAVERY & MILLER MASHUP MIX)'
NOTE: Both are set to orderby=relevance and the video ordering changes when I change max-results; only when max-result is set to 1, the result is correctly ordered.
Anyone know how this can be fixed?
CODE:
(function ($) {
$.fn.YouTubePicker = function (options) {
// default option
var defaults = {
MaxResults: 10 /* number of YouTube results, per "page" */
, OrderBy: 'relevance' /* what to order the results by */
, Author: null /* Author of the video */
, PlayerNumberOp: 1
, ShowNumOfViews: true /* show number of views for the video */
, Thumbnail: 'small' /* small: 120x90 | large: 480 x 360 */
, ControlIdSuffix: '' /* should give the unique string here if you have multiply of YouTubePicker.
Using elements in this plugin will fetch by "id + ControlIdSuffix" */
, ControlQueryHolder: '.YouTubePickerQuery' /* selector to take a element to be query holder (where we take string to query YouTube) */
, ControlSearchButton: '.YouTubePickerSearch' /* selector to take a element to be SearchButton. Click this element to start search. */
, ControlVideoPlayerHolder: '.YouTubePickerVideoPlayer' /* selector to take a element to render VideoPlayer */
, ControlVideoTitleHolder: '.YouTubePickerVideoTitle'
, ControlVideoList: '.YouTubePickerVideoList' /* selector to take a element to render VideoList */
, ControlSelectedUrlHolder: '.YouTubePickerSelectedUrl' /* When user click to select a video, assign the video's url to this input */
, InitVideoUrl: '' /* Init if no search query existed, you can put YouTubeVideoId here or the full Url */
, PlayerWidth: '240' /* setting for player */
, PlayerHeight: '220' /* setting for player */
, AutoPlay: false /* AutoPlay video right after user click an item in the list */
, ShowRelated: false /* show relate video after finish playing */
, AllowFullScreen: true /* enable FullScreen button of Player */
, EnableJsApi: true /* enable Javascript Api*/
};
options = $.extend(defaults, options);
return this.each(function () {
var $container = $(this);
$(options.ControlSearchButton).click(function () {
/// <summary>
/// handler click on search button
/// </summary>
var requestUrl = 'http://gdata.YouTube.com/feeds/api/videos?alt=json&max-results=' + options.MaxResults;
try {
_RequestYouTubeVideos(requestUrl);
} catch (ex) { }
return false;
});
$(options.ControlQueryHolder).keydown(function (event) {
/// <summary>
/// handler press Enter in query textbox
/// </summary>
if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
$(options.ControlSearchButton).trigger('click');
return false;
}
else {
return true;
}
});
//-------------------------------------------------------//
// take the init video and play it if any
// ERASED THIS PART
// $(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(options.InitVideoUrl)));
// _AssignValueToDivOrTextBox(options.ControlSelectedUrlHolder, options.InitVideoUrl);
$('a.navigation').click(function () {
/// <summary>
/// rebind the list whenever user click to change page
/// </summary>
try {
_RequestYouTubeVideos($(this).attr('href'));
} catch (ex) { }
return false;
});
/**
* Util function, assign value to element. Element can be div, span, or input
*/
function _AssignValueToDivOrTextBox(selectorToElement, valueToAssign) {
try {
$(selectorToElement).val(valueToAssign);
} catch (ex) { }
try {
$(selectorToElement).text(valueToAssign);
} catch (ex) { }
}
function _RequestYouTubeVideos(requestUrl) {
/// <summary>
/// fire the jsonp request to get data from YouTube Search API
/// </summary>
var query = $(options.ControlQueryHolder).val();
if (options.Author != null) {
requestUrl += '&author=' + options.Author;
}
if (options.OrderBy != null) {
requestUrl += '&orderby=' + options.OrderBy;
}
if (query != null) {
requestUrl += '&q=' + query;
}
$.ajax({
type: "GET",
url: requestUrl,
cache: false,
dataType: 'jsonp',
global: false,
success: _OnYouTubeSuccess,
error: function (result) {
$(options.ControlVideoList).html('<p>Please fill in a search term</p>');
}
,
ajaxComplete: function (data) {
return false;
}
});
}
function _BuildNavigation(feed) {
/// <summary>
/// Build the navigation link Prev and Next base on the return url in the feed (if existed)
/// </summary>
if (feed.link) {
var nextLink = null;
var prevLink = null;
for (var i = 0; i < feed.link.length; i++) {
var link = feed.link[i];
if (link.rel == 'next') {
nextLink = link.href;
}
else if (link.rel == 'previous') {
prevLink = link.href;
}
}
if (nextLink) {
$('.navigation.next').attr('href', nextLink).show();
}
else {
$('.navigation.next').hide();
}
if (prevLink) {
$('.navigation.prev').attr('href', prevLink).show();
}
else {
$('.navigation.prev').hide();
}
}
}
function formatSecondsAsTime(secs) {
var hr = Math.floor(secs / 3600);
var min = Math.floor((secs - (hr * 3600)) / 60);
var sec = Math.floor(secs - (hr * 3600) - (min * 60));
if (hr < 10) {
hr = "0" + hr;
}
if (min < 10) {
min = "0" + min;
}
if (sec < 10) {
sec = "0" + sec;
}
if (hr) {
hr = "00";
}
return hr + ':' + min + ':' + sec;
}
function _ParseYouTubeFeedItem(feedData) {
/// <summary>
/// Extract what we want from YouTube feedData
/// </summary>
var dto = [];
dto.id = _StripFeature(feedData.link[0].href.substring(feedData.link[0].href.indexOf('=') + 1, feedData.link[0].href.length));
dto.url = feedData.link[0].href;
dto.title = feedData.title.$t;
if (options.Thumbnail == 'large') {
var index = 0; // first thumb is large size
} else {
var index = feedData.media$group.media$thumbnail.length - 1; // take the last small thumb
}
dto.thumbnail = feedData.media$group.media$thumbnail[index].url;
dto.description = feedData.media$group.media$description.$t;
dto.author = feedData.author[0].name.$t;
dto.duration = formatSecondsAsTime(feedData.media$group.media$content[0].duration);
if (feedData.yt$statistics) {
dto.views = feedData.yt$statistics.viewCount;
}
else if (!feedData.yt$statistics) {
dto.views = '0';
}
return dto;
}
/**
* Process the json result, render the list
*/
function _OnYouTubeSuccess(result) {
var feed = result.feed;
var rfeed = feed.entry || [];
var relVideos = [];
var $ctrVideoList = $(options.ControlVideoList);
// build the navigation
_BuildNavigation(feed);
if (rfeed.length > 0) {
$(rfeed).each(function (i) {
/// <summary>
/// from feeditem from YouTube, build the video data object
/// </summary>
relVideos[i] = _ParseYouTubeFeedItem(rfeed[i]);
}).ready(function () {
relVideos.sort(_ArraySort);
var $itemsHtml = $('<div>'); // temporary DOM node to append VideoItem to
$(relVideos).each(function (i) {
/// <summary>
/// Create each list item
/// </summary>
$itemsHtml.append('<li class="VideoItem">');
videoItem = $itemsHtml.find('.VideoItem:last');
videoItem.append('<div class="VideoThumb">');
videoThumb = videoItem.find('.VideoThumb');
$('<a>').addClass('YouTubelink').attr('href', relVideos[i].url).append('<img src="' + relVideos[i].thumbnail + '">').appendTo(videoThumb);
videoItem.append('<div class="VideoInfo">');
videoInfo = videoItem.find('.VideoInfo');
videoInfo.append('<strong>' + relVideos[i].title + ' </strong><br /><span class="VideoNumOfViews">' + relVideos[i].views + ' views</span><br /><span></span>' + relVideos[i].duration + '<br />');
});
// clear the list
$ctrVideoList.empty().append($itemsHtml.children());
});
// load inital video after finish rendering the list
// take the first video in the list, take it link, take it href, assign to the Player
// ERASED THIS PART
//var firstVid = $ctrVideoList.children("li:first-child").addClass("selected").find("a").eq(1).attr("href");
//$(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(firstVid)));
$ctrVideoList.find("li a").unbind('click').bind('click', function () {
/// <summary>
/// load video on click of a in li
/// </summary>
try {
var selectedUrl = $(this).attr("href");
// return the selectedUrl to outside (try catch to avoid error in IE)
_AssignValueToDivOrTextBox(options.ControlSelectedUrlHolder, selectedUrl);
$(options.ControlVideoPlayerHolder + "").html(_GetPlayerHtml(_GetYouTubeIdFromUrl(selectedUrl)));
// DIT IS EEN TEST
$(options.ControlVideoTitleHolder + "").html(_GetTitleHtml(_GetYouTubeIdFromUrl(selectedUrl)));
$(this).parent().parent().parent("ul").find("li.selected").removeClass("selected");
$(this).parent().parent("li").addClass("selected");
} catch (ex) { }
return false;
});
} else {
/* if we have no YouTube videos returned, let's tell user */
$ctrVideoList.html('<p>There is no result</p>');
}
} // end _OnYouTubeSuccess
function _ArraySort(a, b) {
if (a.title < b.title) {
return -1;
}
else if (a.title > b.title) {
return 1;
}
else {
return 0;
}
}
function _StripFeature(vidID) {
var featureLoc = vidID.indexOf('&feature=YouTube_gdata');
if (featureLoc >= 0) {
return vidID.substring(0, featureLoc);
} else {
return vidID;
}
}
/**
* Create a Player HTML code to play an YouTubeID, and return it HTML string
*/
function _GetPlayerHtml(YouTubeVideoId) {
// if YouTubeVideoId is null or empty, we provide an empty div with same dimension of the Player
// This will fix a bug of IE (IE will load the swf forever if object movie is empty and/or embbed src is empty
if (!YouTubeVideoId) {
return '<div style="width:240px;height:220px">';
}
var html = '';
var PlayerNumber = options.PlayerNumberOp;
html += '<object height="220" width="240">';
html += '<param name="movie" value="http://www.YouTube.com/v/'+YouTubeVideoId+'?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1"> </param>';
html += '<param name="wmode" value="transparent"> </param>';
// I HAVE CHANGED THIS
html += '<iframe onload="floaded'+PlayerNumber+'()" id="player'+PlayerNumber+'" width="240" height="220" src="http://www.youtube.com/embed/'+YouTubeVideoId+'?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1" frameborder="0" allowfullscreen> </iframe>';
html += '</object>';
return html;
};
function _GetTitleHtml(YouTubeVideoId) {
var html = '';
var PlayerNumber = options.PlayerNumberOp;
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+YouTubeVideoId+'?v=2&alt=jsonc',function(data,status,xhr){
var video_title1=data.data.title;
var finaltext1="<div id='title1'><h5 class='redtext'>USER SELECTED</h5><h5>"+video_title1+"</h5></div>";
$('#YouTubePickerVideoTitle'+PlayerNumber+'').html(finaltext1);
});
return html;
};
function _GetYouTubeIdFromUrl(url) {
/// <summary>
/// use RegEx too grab a YouTube id from a (clean, no querystring) url (thanks to http://jquery-howto.blogspot.com/2009/05/jYouTube-jquery-YouTube-thumbnail.html)
/// <return>empty string if cannot match.</return>
/// </summary>
if (url && url != '') {
try {
var ytid = url.match("[\\?&]v=([^&#]*)");
ytid = ytid[1];
return ytid;
}
catch (ex) { }
}
return '';
};
});
};
})(jQuery);

Deniz.
I'm not sure but guess Youtube uses your preferences to filter video searches.
Try other kind of filter and see what you get.

Related

Custom Parameters get cleared canvas to Json

I am adding svg to canvas and want to set custom Element Parameters. I shows custom parameter when we console log getActiveObject() but when we use canvas.toJSON() Element Parameter node values does not change.
var canvas = new fabric.Canvas('designcontainer'),
/* Save additional attributes in Serialization */
var ElementParameters = {
ElementType:'',
imageType:'',
top:'',
left:'',
colors:'',
isBaseTier:'',
atLevel:''
};
fabric.Object.prototype.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
ElementParameters:{
ElementType:'',
imageType:'',
top:'',
left:'',
colors:'',
isBaseTier:'',
atLevel:''
},
});
};
})(fabric.Object.prototype.toObject);
/* End : Save additional attributes in Serialization */
var Designer = {
addElement: function(e,p){ /* e = element, image src | p = parameters set for image */
if(p.imageType == "svg"){
if(p.ElementType == "caketier"){
var group = [];
console.log('Before ');
console.log(ElementParameters);
$.extend(ElementParameters,p);
console.log('After ');
console.log(ElementParameters);
fabric.loadSVGFromURL(e,function(objects,options){
var shape = fabric.util.groupSVGElements(objects,options);
var bound = shape.getBoundingRect();
shape.set({
left: p.left,
top: p.top,
width:bound.width+2,
height:bound.height,
angle:0,
centeredScaling:true,
ElementParameters:ElementParameters
});
if(shape.paths && baseColor.length > 0){
for(var i = 0;i<shape.paths.length;i++) shape.paths[i].setFill(baseColor[i]);
}
canvas.add(shape);
shape.setControlsVisibility(HideControls);
canvas.renderAll();
},function(item, object) {
object.set('id',item.getAttribute('id'));
group.push(object);
});
}
}
}
}
$(".tierbox").on('click',function(){
var i = $(this).find('img'),
src = i.attr('src'),
param = i.data('parameters');
Designer.addElement(src,param);
});
Now when I call JSON.stringify(json), Element Parameter node does not get overwrite with values set in shape.set() method.
Replace fabric.Object.prototype.toObject = (function (toObject) { ... } to
fabric.Object.prototype.toObject = (function (toObject) {
return function () {
return fabric.util.object.extend(toObject.call(this), {
ElementParameters:this.ElementParameters
});
};
})(fabric.Object.prototype.toObject);

String.fromCharCode and String.fromCodePoint are not working in react native app's apk

String.fromCharCode and String.fromCodePoint both are working fine in chrome developer tools and in the emulator but when i am generating the apk and running it on the actual android device, its not working.
According to MDN's String.fromCodePoint doc:
The String.fromCodePoint method has been added to ECMAScript 2015 and may not be supported in all web browsers or environments yet. Use the code below for a polyfill:
*! http://mths.be/fromcodepoint v0.1.0 by #mathias */
if (!String.fromCodePoint) {
(function() {
var defineProperty = (function() {
// IE 8 only supports `Object.defineProperty` on DOM elements
try {
var object = {};
var $defineProperty = Object.defineProperty;
var result = $defineProperty(object, object, object) && $defineProperty;
} catch(error) {}
return result;
}());
var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
var fromCodePoint = function() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (
!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) != codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
if (defineProperty) {
defineProperty(String, 'fromCodePoint', {
'value': fromCodePoint,
'configurable': true,
'writable': true
});
} else {
String.fromCodePoint = fromCodePoint;
}
}());
}
so you can try to polyfill String.fromCodePoint in your file

Google Api Nearby Places on change of type, layer removed, but advertising stays, how can I remove the complete layer without reloading the page

I have custom code to create a nearby search of places on google map.
Each search type creates a new layer, removed when selecting a different search type, my problem is, even thought he layer is removed, here in Thailand we have "Google partners advertising" show dependant on the search type and this "Layer" doesnt get removed, but added to when creating a new search layer.
This is the code I use to create the search (in part):
Creating a layer (Google):
<div id="map_layers_google">
<input type="checkbox" name="map_google" id="map_google_restaurant" class="box" onclick="Propertywise.Maps.getDataWithinBounds('google_restaurant');" value="google_restaurant">
</div>
getDataWithinBounds: function(layer_name, except_this_area) {
if (!Propertywise.Design.is_ie8_or_less) {
this.layers_on_map[layer_name] = true;
this.getEntitiesWithinBounds(layer_name);
}
getEntitiesWithinBounds: function(entity_name) {
var $this = this;
if (!this.getBounds()) {
setTimeout(function() {
$this.getEntitiesWithinBounds(entity_name);
}, 20);
} else {
var layer_name, category;
var $this_input_el = jQuery("#map_" + entity_name);
jQuery("#map_updating").fadeIn('fast');
if (entity_name.indexOf('google') != -1) {
layer_name = "google";
category = entity_name.replace("google_", "");
} else if (entity_name.indexOf('school') != -1) {
layer_name = "schools";
category = entity_name.replace("schools_", "");
} else if (entity_name.indexOf('events') != -1) {
layer_name = "events";
category = entity_name.replace("events_", "");
} else {
layer_name = "transport";
this.toggleTransitLayer();
}
jQuery("#map_layers_" + layer_name + " input").each(function(index, value) {
var el_id = jQuery(this).attr("id");
var el_entity_name = el_id.replace("map_", "");
Propertywise.Maps.layers_on_map[el_entity_name] = false;
if (jQuery(this).is(":checked") && el_entity_name != entity_name) {
jQuery(this).attr("checked", false);
}
if (jQuery(this).is(":checked") && el_entity_name == entity_name) {
Propertywise.Maps.layers_on_map[entity_name] = true;
}
});
if (jQuery("#map_" + entity_name).is(':checked') || Propertywise.this_page == "school") {
if (layer_name == "google") {
infoWindow = new google.maps.InfoWindow();
Propertywise.Maps.removeMarkers(layer_name);
var request = {
bounds: Propertywise.Maps.map.getBounds(),
types: [category]
};
service = new google.maps.places.PlacesService(Propertywise.Maps.map);
service.radarSearch(request, function(results, status) {
jQuery("#map_updating").fadeOut('fast');
if (status != google.maps.places.PlacesServiceStatus.OK) {
return;
}
for (var i = 0, result; result = results[i]; i++) {
Propertywise.Maps.createMarker(result.geometry.location.lat(), result.geometry.location.lng(), {
place: result,
type: category
});
}
});
}
} else {
this.removeMarkers(layer_name);
jQuery("#map_updating").fadeOut('fast');
}
}
}
And this is the setup and remove each layer:
setUpLayers: function() {
var $this = this;
jQuery.each(this.layers, function(layer_name, value) {
Propertywise.Ajax.requests[layer_name] = [];
$this.layers[layer_name] = [];
});
},
removeMarkers: function(layer_name) {
if (Propertywise.Maps.map) {
var layer = this.layers[layer_name];
for (var i = 0; i < layer.length; i++) {
layer[i].setMap(null);
}
layer = [];
}
}
Here is link to screen shot of the problem.
screenshot
Question is, can anyone help with either changing the above to remove the complete layer(not just marker layer) or advise how to remove the advertising.. I understand this is part of terms of Google to display, but its unprofessional and looks terrible.
Best
Malisa

Parse URL (ActionScript 3.0)

I would like to know how would one parse an URL.
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
I need to get "this_is_what_i_want/even_if_it_has_slashes"
How should I do this?
Thanks!
Try this :
var u:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes',
a:Array = u.split('/'),
s:String = ''
for(var i=0; i<a.length; i++){
if(i > 3){
s += '/'+a[i]
}
}
trace(s) // gives : /morethings/this_is_what_i_want/even_if_it_has_slashes
Another approach would be using Regex like this:
.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)
(Breakdown of the components.)
This looks for a pattern where it skips whatever comes before the domain name (doesn't matter if the protocol is specified or not), skips the domain name + TLD, skips any port number, and skips the first two sub path elements. It then selects whatever comes after it but skips any query strings.
Example: http://regexr.com/39r69
In your code, you could use it like this:
var url:String = "protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes";
var urlExp:RegExp = /.*?mydomain\.com[^\/]*\/[^\/]+\/[^\/]+\/([^?]*)/g;
var urlPart:Array = urlExp.exec(url);
if (urlPart.length > 1) {
trace(urlPart[1]);
// Prints "this_is_what_i_want/even_if_it_has_slashes"
} else {
// No matching part of the url found
}
As you can see on the regexr link above, this captures the part "this_is_what_i_want/even_if_it_has_slashes" for all of these variations of the url:
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html
protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes.html?hello=world
mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes
protocol://subdomain.mydomain.com:8080/something/morethings/this_is_what_i_want/even_if_it_has_slashes
Edit: Fixed typo in regexp string
Simple way,
var file:String = 'protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes';
var splitted:Array = file.split('/');
var str1:String = splitted.splice(3).join('/'); //returns 'something/morethings/this_is_what_i_want/even_if_it_has_slashes'
var str1:String = splitted.splice(5).join('/'); //returns 'this_is_what_i_want/even_if_it_has_slashes'
If you want to be a little more flexible in the feature (e.g. you need the domain), you can use my Url class.
Class for URL parsing
package
{
import flash.net.URLVariables;
public class Url
{
protected var protocol:String = "";
protected var domain:String = "";
protected var port:int = 0;
protected var path:String = "";
protected var parameters:URLVariables;
protected var bookmark:String = "";
public function Url(url:String)
{
this.init(url);
}
protected function splitSingle(value:String, c:String):Object
{
var temp:Object = {first: value, second: ""};
var pos:int = value.indexOf(c);
if (pos > 0)
{
temp.first = value.substring(0, pos);
temp.second = value.substring(pos + 1);
}
return temp;
}
protected function rtrim(value:String, c:String):String
{
while (value.substr(-1, 1) == c)
{
value = value.substr(0, -1);
}
return value;
}
protected function init(url:String):void
{
var o:Object;
var urlExp:RegExp = /([a-z]+):\/\/(.+)/
var urlPart:Array = urlExp.exec(url);
var temp:Array;
var rest:String;
if (urlPart.length <= 1)
{
throw new Error("invalid url");
}
this.protocol = urlPart[1];
rest = urlPart[2];
o = this.splitSingle(rest, "#");
this.bookmark = o.second;
rest = o.first;
o = this.splitSingle(rest, "?");
o.second = this.rtrim(o.second, "&");
this.parameters = new URLVariables();
if (o.second != "")
{
try
{
this.parameters.decode(o.second);
}
catch (e:Error)
{
trace("Warning: cannot decode URL parameters. " + e.message + " " + o.second);
}
}
rest = o.first
o = this.splitSingle(rest, "/");
if (o.second != "")
{
this.path = "/" + o.second;
}
rest = o.first;
o = this.splitSingle(rest, ":");
if (o.second != "")
{
this.port = parseInt(o.second);
}
else
{
switch (this.protocol)
{
case "https":
this.port = 443;
break;
case "http":
this.port = 80;
break;
case "ssh":
this.port = 22;
break;
case "ftp":
this.port = 21;
break;
default:
this.port = 0;
}
}
this.domain = o.first;
}
public function getDomain():String
{
return this.domain;
}
public function getProtocol():String
{
return this.protocol;
}
public function getPath():String
{
return this.path;
}
public function getPort():int
{
return this.port;
}
public function getBookmark():String
{
return this.bookmark;
}
public function getParameters():URLVariables
{
return this.parameters;
}
}
}
Example usage
try {
var myUrl:Url = new Url("protocol://mydomain.com/something/morethings/this_is_what_i_want/even_if_it_has_slashes");
trace("Protocol: " + myUrl.getProtocol());
trace("Domain: " + myUrl.getDomain());
trace("Path: " + myUrl.getPath());
trace("What you want: " + myUrl.getPath().split("/").splice(2).join("/") );
} catch (e:Error) {
trace("Warning: cannot parse url");
}
Output
Protocol: protocol
Domain: mydomain.com
Path: /something/morethings/this_is_what_i_want/even_if_it_has_slashes
What you want: morethings/this_is_what_i_want/even_if_it_has_slashes
Description
The init function checks with the regular expression if the given url starts with some letters (the protocol) followed by a colon, two slashes and more characters.
If the url contains a hash letter, everything behind its fist occurrence is taken as a bookmark
If the url contains a question mark, everything behind its fist occurrence is taken as key=value variables and parsed by the URLVariables class.
If the url contains a slash, everything behind its first occurrence is taken as the path
If the rest (everything between the last protocol slash and the first slash of the path) contains a colon, everything behind it will be converted to an integer and taken as the port. If the port is not set, a default will be set in dependency of the protocol
The rest is the domain
For answering your question, I use the path of the given url, split it by slash, cut of the 'something' and join it by slash.

as3 why is my public var changing?

I have a var called "currentMystery" I have reduced the issue down to these two functions
I believe. Anyway, the first time through it works and traces a var from an Array... but the second time through something is changing it to [Event type="soundComplete" bubbles=false cancelable=false eventPhase=2]
What in the code is changing this or what am I doing wrong?
Thanks so much!
Any ideas on how to keep it as the same var as it assigned here:
currentMystery = "" + Mystries[4] + "";
...
public static var Mystries:Array = new Array("null","Joyful","Luminous","Sorrowful","Glorious");
public function checkDecade(e:Event = null)
{
if (decadeCount < 6)
{
Announce = true;
currentMystery = "" + Mystries[4] + "";
prayDecade(currentMystery);
}
}
public function prayDecade(currentMystery:String)
{
//// MY ISSUE IS WITH currentMystery. First time through
//// it works but the second through it is changing to
//// something like [Event type="soundComplete" bubbles=false etc...
trace("Pray Decade called: " +currentMystery);
if (Announce)
{
/// Sets PAUSE before Announc || Add features later to all prayers
setTimeout(function()
{
MainDoc.cPrayer.text = currentMystery;
trace("Called Announce"+decadeCount);
trace("Called Announce: Mystery: " + currentMystery+" Current Decade: " +decadeCount);
theAnnounce = new Sound();
theAnnounce.load(new URLRequest("audio/Rosary/Announce/"+currentMystery+"/"+decadeCount+".mp3"));
Praying = theAnnounce.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
Announce = false;
}, 2000);
}
else
{
if (prayerCount==0)
{
trace("Our Father " + decadeCount);
//trace(love);
Begin = true;
/// Sets PAUSE before Our Father || Add features later to all prayers
setTimeout(function()
{
Begin = true;
ourFather();
}, 2000);
}
if (prayerCount >0 && prayerCount<11)
{
trace("Hail Mary " + prayerCount);
Begin = true;
hailMary();
}
if (prayerCount==11)
{
trace("Glory Be... " + prayerCount);
Begin = true;
gloryBe();
}
if (prayerCount==12)
{
trace("Oh My Jesus... " + prayerCount);
Begin = true;
ohMyJesus();
}
function ourFather(e:Event = null)
{
if (Begin)
{
Praying = OFB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, ourFather );
}
else
{
Praying = OFE.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
prayerCount++;
}
Begin = false;
}
function hailMary(e:Event = null)
{
if (Begin)
{
Praying = HMB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, hailMary );
}
else
{
Praying = HME.play();
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
prayerCount++;
}
Begin = false;
}
function gloryBe(e:Event = null)
{
if (Begin)
{
Praying = GBB.play();
Praying.addEventListener(Event.SOUND_COMPLETE, gloryBe );
}
else
{
Praying = GBE.play();
Praying.addEventListener(Event.SOUND_COMPLETE, checkDecade );
prayerCount++;
}
Begin = false;
}
function ohMyJesus(e:Event = null)
{
Praying = OMJ.play();
Praying.addEventListener(Event.SOUND_COMPLETE, checkDecade );
prayerCount = 0;
decadeCount++;
}
}//End if Else
}
You're using the prayDecade method as a handler for the sound complete event as well as calling it directly in your code. When it is invoked as an event handler, the parameter it receives is an event object which is being cast to a string and overwriting your public variable within the local (prayDecade function) scope.
I think if you update the function as follows you'll get the results you expect (assuming currentMystery is a public variable in the class scope:
public function prayDecade(e:Event)
{
trace("Pray Decade called: " + currentMystery);
// ....
}
And when you invoke the method directly, don't pass the variable:
// Assuming currentDecade is in scope in the prayDecade method
prayDecade(/*currentMystery*/);
What in the code is changing this or what am I doing wrong?
Event handler for the 'SoundChannel' is wrong.
Praying.addEventListener(Event.SOUND_COMPLETE, prayDecade );
In the prayDecade as an argument will be passed event object (Event.SOUND_COMPLETE), not a string as you are waiting for. So [Event type="soundComplete" bubbles=false cancelable=false eventPhase=2] is a String representation of event.